iPhoneタイル色々

タイルの色をランダムに変えて気に入ったパターンを探すiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SpriteKit;

@interface ViewController ()

@property (nonatomic, weak) SKScene *scene;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createColorfulRectangle];

    [self createButton];

}

– (void)setupScene {

    SKView *sv = [[SKView alloc] initWithFrame:self.view.bounds];

    SKScene *s = [SKScene sceneWithSize:sv.frame.size];

    s.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];

    [sv presentScene:s];

    [self.view addSubview:sv];

    self.scene = s;

}

– (void)createColorfulRectangle {

    

    [self.scene enumerateChildNodesWithName:@”triangle” usingBlock:^(SKNode *node, BOOL *stop) {

        node.name = @”old”;

        node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];

        [node.physicsBody applyForce:CGVectorMake(0, 5)];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [node removeFromParent];

        });

    }];

    

    float l = CGRectGetMaxX(self.view.bounds) / 10.0;

    UIBezierPath *path = [UIBezierPath bezierPath];

    [path moveToPoint:CGPointMake(-l * 0.5,  l * 0.5)];

    [path addLineToPoint:CGPointMake(l * 0.5,  l * 0.5)];

    [path addLineToPoint:CGPointMake(-l * 0.5,  -l * 0.5)];

    [path closePath];

    

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

        float x = (i % 10) * l + l * 0.5;

        float y = (i / 10) * l + 200;

        

        for (int j=0; j<2; j++) {

            SKShapeNode *triangle = [SKShapeNode shapeNodeWithPath:path.CGPath];

            triangle.name = @”triangle”;

            triangle.zRotation = j * M_PI;

            triangle.path = path.CGPath;

            triangle.position = CGPointMake(x, y);

            

            float hue = arc4random_uniform(100) * 0.01;

            triangle.fillColor = [UIColor colorWithHue:hue saturation:0.5 brightness:1 alpha:1];

            [self.scene addChild:triangle];

            

            triangle.alpha = 0;

            [triangle runAction:[SKAction fadeInWithDuration:1.0]];

        }

    }

}

– (void)createButton {

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];

    [btn setTitle:@”change” forState:UIControlStateNormal];

    btn.titleLabel.font = [UIFont boldSystemFontOfSize:40];

    [btn sizeToFit];

    btn.center = CGPointMake(CGRectGetMaxX(self.view.bounds) * 0.75, CGRectGetMaxY(self.view.bounds) – 150);

    btn.transform = CGAffineTransformMakeRotation(M_PI*0.25);

    [self.view addSubview:btn];

    

    [btn addTarget:self action:@selector(change) forControlEvents:UIControlEventTouchUpInside];

}

– (void)change {

    [self createColorfulRectangle];

}

@end