iPhone雪ツリー

線で描いてあるクリスマスツリーを指でなぞると、雪が落ちて色が出てくるよ。と言う感じのiPhoneアプリのサンプルコードを描いてみます。


今回使った画像


サンプルを動かしてみた動画

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

}

– (void)viewDidAppear:(BOOL)animated

{

    [self createColoredView];

    [self createWhiteView];

    [self createOutlineView];

}

– (void)createOutlineView

{

    UIImage *img = [UIImage imageNamed:@”tree_bw”];

    UIImageView *v = [[UIImageView alloc] initWithImage:img];

    v.center = CGPointMake(240, 180);

    [self.view addSubview:v];

}

– (void)createWhiteView

{

    int max = 10000;

    for (int i=0; i<max; i++) {

        CALayer *snow = [CALayer layer];

        snow.name = @”snow”;

        snow.backgroundColor = [UIColor whiteColor].CGColor;

        float x = 10.0 * (i % 48);

        float y = 10.0 * (i / 48);

        snow.frame = CGRectMake(x, y, 15, 15);

        snow.cornerRadius = 7.5;

        [self.view.layer addSublayer:snow];

    }

}

– (void)createColoredView

{

    UIImage *img = [UIImage imageNamed:@”tree_color”];

    UIImageView *v = [[UIImageView alloc] initWithImage:img];

    v.center = CGPointMake(240, 180);

    [self.view addSubview:v];

}

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

{

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

    [self.view.layer.sublayers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        if ([[obj name] isEqual:@”snow”]) {

            if (CGRectContainsPoint([obj frame], p)) {

                [obj setName:@””];

                [self performSelector:@selector(drop:) withObject:obj afterDelay:0.01];

            }

        }

    }];

}

– (void)drop:(CALayer*)layer

{

    layer.shadowColor = [UIColor blackColor].CGColor;

    layer.shadowOffset = CGSizeMake(1.0, 1.0);

    layer.shadowRadius = 1.0;

    layer.shadowOpacity = 1.0;

    

    CABasicAnimation* fall = [CABasicAnimation animationWithKeyPath:@”position.y”];

    float start = layer.position.y;

    layer.position = CGPointMake(layer.position.x, 400);

    

    fall.fromValue = @(start);

    fall.toValue = @400;

    fall.duration = 3.0;

    [layer addAnimation:fall forKey:nil];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end