iPhone雨縞模様

雨縞模様のまんなかに、水玉が落ちてくるというかんじで、iPhoneアプリを描いてみます。


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

サンプルコード

#import “ViewController.h”

@interface ViewController ()

@property (strong, nonatomic) UIImageView *drop;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.6 alpha:1];

    

    [self createRain];

    

    [self createRainDrop];

    

    [self start];

}

– (void)createRain

{

    UIBezierPath *path = [UIBezierPath bezierPath];

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

        if (i == 4 || i == 5 || i == 6) {

            continue;

        }

        float x = i * 30 + 10;

        [path moveToPoint:CGPointMake(x, 0)];

        [path addLineToPoint:CGPointMake(x, 568)];

        [path moveToPoint:CGPointMake(x+4, 5)];

        [path addLineToPoint:CGPointMake(x+4, 568)];

    }

    

    CAShapeLayer *sl = [CAShapeLayer layer];

    sl.strokeColor = [UIColor whiteColor].CGColor;

    sl.path = path.CGPath;

    sl.lineWidth = 1;

    sl.lineDashPattern = @[@30, @10];

    [self.view.layer addSublayer:sl];

}

– (void)createRainDrop

{

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

        float y = i * 30 + 40;

        UIView *mark = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

        mark.layer.cornerRadius = 5;

        mark.center = CGPointMake(160, y);

        mark.backgroundColor = [UIColor whiteColor];

        mark.tag = i + 1;

        [self.view addSubview:mark];

    }

    

    UIImage *dropImg = [UIImage imageNamed:@”drop”];

    self.drop = [[UIImageView alloc] initWithImage:dropImg];

    self.drop.frame = CGRectMake(0, 0, 25, 25);

    self.drop.center = CGPointMake(160, 40);

    [self.view addSubview:self.drop];

}

– (void)start

{

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

}

– (void)tick:(NSTimer*)sender

{

    float currentY = self.drop.center.y;

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

        UIView *v = obj;

        if (v.tag > 0) {

            if (v.center.y == currentY) {

                int next = v.tag % 16 + 1;

                UIView *nextMark = [self.view viewWithTag:next];

                [UIView animateWithDuration:0.2 animations:^{

                    self.drop.center = nextMark.center;

                }];

            }

        }

    }];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end