黒板に好きなように線を描いてみよう。
ゆびを離すと黄、緑、赤の順番で同じ形の線を
黒板が描いてくれるよ。(やまびこ的な。。。)
という感じの子供むけiPhoneアプリのサンプルを作ってみた。

ポイント
CAShapeLayerのstrokeEndを使って、
線を書き直すアニメーションにしています。
0と1を3回タイマー内で行ったり来たりすることで、
色を変えて書き直し。

環境
今回つくったiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています。


サンプルコード


#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    UIBezierPath *path;

    CAShapeLayer *sl;

    NSTimer *timer;

    float end;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    

    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];

    label.text = @”Redraw”;

    label.font = [UIFont boldSystemFontOfSize:50];

    label.textColor = [UIColor darkGrayColor];

    label.backgroundColor = [UIColor clearColor];

    label.transform = CGAffineTransformMakeRotation(M_PI * 0.3);

    [self.view addSubview:label];

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [timer invalidate];

    [sl removeFromSuperlayer];

    

    CGPoint p = [[touches anyObject] locationInView:self.view];

    path = [[UIBezierPath alloc] init];

    [path moveToPoint:p];

    

    sl = [[CAShapeLayer alloc] initWithLayer:self.view];

    sl.strokeColor = [UIColor whiteColor].CGColor;

    sl.fillColor = [UIColor clearColor].CGColor;

    sl.lineWidth = 10.0;

    [self.view.layer addSublayer:sl];

}

– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

    CGPoint p = [[touches anyObject] locationInView:self.view];

    [path addLineToPoint:p];

    

    sl.path = path.CGPath;

}

– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

{    

    [self start];

}

– (void)start

{

    end = 0;

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

}

– (void)tick:(NSTimer*)sender

{

    float velocity = 0.05;

    

    [CATransaction begin];

    [CATransaction setDisableActions: YES];

    

    if (end < 1.0) {

        sl.strokeEnd -= velocity;

    } else if (end < 2.0){

        sl.strokeColor = [UIColor yellowColor].CGColor;

        sl.strokeEnd += velocity;

    } else if (end < 3.0) {

        sl.strokeEnd -= velocity;

    } else if (end < 4.0){

        sl.strokeColor = [UIColor greenColor].CGColor;

        sl.strokeEnd += velocity;

    } else if (end < 5.0) {

        sl.strokeEnd -= velocity;

    } else if (end < 6.0){

        sl.strokeColor = [UIColor redColor].CGColor;

        sl.strokeEnd += velocity;

    } else {

        [timer invalidate];

    }

    

    [CATransaction commit];

    

    end += velocity;

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end