壁紙的な感じでカラフルな数字をアニメーションさせてみる。

(XcodeのiOS6 Simulatorで試しています。)

ポイント

・数字ラベルは、背景をカラフルにして、レイヤーに丸角

・数字を画面上にランダムに配置

・NSTimer で一秒周期で、動かす

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    NSTimer *timer;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    [self createNumber];

    

    [self start];

}

– (void)createNumber

{

    // パターン色

    NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor blueColor], [UIColor greenColor], [UIColor orangeColor], [UIColor purpleColor], [UIColor yellowColor], nil];

    

    for (int i=10; i>0; i–) {

        // ランダム

        int colorIndex = arc4random() % [colors count];

        UIColor *color = [colors objectAtIndex:colorIndex];

        float x = 10 * (arc4random() % 25) + 10;

        float y = 20 * (arc4random() % 20) + 10;

        float size = 10 * (arc4random() % 10) + 40;

        UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, size, size)];

        numberLabel.text = [NSString stringWithFormat:@”%d”, i];

        numberLabel.textColor = [UIColor whiteColor];

        numberLabel.font = [UIFont boldSystemFontOfSize:size * 0.7];

        numberLabel.backgroundColor = color;

        numberLabel.layer.cornerRadius = size * 0.5;

        numberLabel.textAlignment = 1; // center

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

        numberLabel.layer.borderWidth = 2.0;

        [self.view addSubview:numberLabel];

    }

}

– (void)start

{

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

    [timer fire];

}

– (void)moveNumbers

{

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

        float num = arc4random() % 8; // 8方向のいずれかに動かす

        float x = v.center.x + 80 * sin((M_PI / 4.0) * num);

        float y = v.center.y + 80 * cos((M_PI / 4.0) * num);

        CGPoint old = v.center;

        

        [UIView animateWithDuration:0.5 animations:^{

            v.center = CGPointMake(x, y);

        } completion:^(BOOL finished) {

            [UIView animateWithDuration:0.5 animations:^{

                v.center = old;

            }];

        }];

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    [timer invalidate];

    timer = nil;

}

@end