iPhone四角カオス

押した部分に、四角いビームがクルクルまわって飛んでいくiPhoneアプリを描いてみます。たくさん画面を押すと、まわる四角が大量になってきていい感じにカオスな絵になります。


動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()

@property (strong, nonatomic) NSMutableArray *arr;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blueColor];

    [self setLongPressGesture];

    [self startTimer];

}

– (NSArray*)arr

{

    if (!_arr) {

        _arr = [[NSMutableArray alloc] init];

    }

    return _arr;

}

– (void)setLongPressGesture

{

    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];

    lpgr.minimumPressDuration = 0;

    [self.view addGestureRecognizer:lpgr];

}

– (void)longPress:(UILongPressGestureRecognizer*)gr

{

    if (gr.state == UIGestureRecognizerStateBegan) {

        NSValue *point = [NSValue valueWithCGPoint:[gr locationInView:self.view]];

        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(shoot:) userInfo:point repeats:YES];

        [self.arr insertObject:timer atIndex:0];

        

    } else if (gr.state == UIGestureRecognizerStateEnded) {

        NSTimer *t = [self.arr lastObject];

        [self.arr removeObject:t];

        [self performSelector:@selector(stopShoot:) withObject:t afterDelay:2.0];

    }

}

– (void)shoot:(NSTimer*)sender

{

    UIView *shot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

    shot.backgroundColor = [UIColor clearColor];

    shot.layer.borderColor = [UIColor whiteColor].CGColor;

    shot.layer.borderWidth = 2;

    shot.center = [sender.userInfo CGPointValue];

    [self.view addSubview:shot];

}

– (void)stopShoot:(NSTimer*)timer

{

    [timer invalidate];

    timer = nil;

}

– (void)startTimer

{

    [NSTimer scheduledTimerWithTimeInterval:1.0/30.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];

}

– (void)tick:(NSTimer*)sender

{

    for (UIView *v in self.view.subviews) {

        CGAffineTransform t = v.transform;

        t = CGAffineTransformScale(t, 0.8, 0.8);

        v.transform = CGAffineTransformRotate(t, M_PI/15.0);

        v.layer.borderWidth = v.layer.borderWidth / 0.9;

        v.tag ++;

        

        if (v.tag > 20) {

            [v removeFromSuperview];

        }

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end