iPhone 黒い三角形

黒い三角形をランダムに配置して、簡単な幾何学模様をつくるiPhoneアプリを書いてみます。


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

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    UIBezierPath *path;

    CAShapeLayer *sl;

    float edge;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor yellowColor];

    edge = 20;

    [self randomTriangles];

    

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];

    [self.view addGestureRecognizer:tap];

}

– (void)randomTriangles

{

    

    path = [UIBezierPath bezierPath];

    sl = [CAShapeLayer layer];

    sl.fillColor = [UIColor blackColor].CGColor;

    [self.view.layer addSublayer:sl];

    

    int rows = 320 / edge;

    int cols = 568 / edge;

    

    for (int i=0; i<(rows * cols); i++) {

        if (arc4random() % 2) {

            float x = (i % rows) * (edge + 1);

            float y = (i / rows) * (edge + 1);

            

            double delayInSeconds = 0.01;

            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

                [self drawTriangle:CGPointMake(x, y)];

            });

        }

    }

}

– (void)drawTriangle:(CGPoint)o

{

    float r = (edge/2) / cos(M_PI/6.0);

    CGPoint p1 = CGPointMake(o.x, o.y – r);

    CGPoint p2 = CGPointMake(o.x + r * cos(M_PI/6.0), o.y + r * sin(M_PI/6.0));

    CGPoint p3 = CGPointMake(o.x – r * cos(M_PI/6.0), o.y + r * sin(M_PI/6.0));

    

    [path moveToPoint:p1];

    [path addLineToPoint:p2];

    [path addLineToPoint:p3];

    [path closePath];

    [CATransaction begin];

    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];

    sl.path = path.CGPath;

    [CATransaction commit];

}

– (void)tap

{

    [sl removeFromSuperlayer];

    edge = arc4random() % 20 + 5;

    [self randomTriangles];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end