iPhone 鹿子文様

鹿の子文様で楽しむiPhoneアプリを描いてみます。


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

サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController ()

@property (strong, nonatomic) CALayer *mask;

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];

    [self createMonyou];

    

    self.mask = [CALayer layer];

    self.mask.backgroundColor = [UIColor blackColor].CGColor;

    self.mask.frame = CGRectMake(50, 50, 200, 200);

    self.mask.cornerRadius = 100;

    self.view.layer.mask = self.mask;

}

– (void)createMonyou

{

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

        float x = (i%8) * 40;

        float y = (i/8) * 30;

        if ((i/8) % 2) {

            x += 20;

        }

        UIView *kanoko = [self createKanoko];

        kanoko.center = CGPointMake(x, y);

    }

}

– (UIView*)createKanoko

{

    UIBezierPath *path = [UIBezierPath bezierPath];

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

        float x = 24 + (arc4random() % 2);

        float y = 24 + (arc4random() % 2);

        CGPoint p = CGPointMake(x, y);

        [path addArcWithCenter:p radius:arc4random()%5+5 startAngle:0 endAngle:2*M_PI clockwise:YES];

    }

    

    CAShapeLayer *sl = [CAShapeLayer layer];

    sl.fillColor = [UIColor whiteColor].CGColor;

    sl.path = path.CGPath;

    

    CALayer *black = [CALayer layer];

    black.frame = CGRectMake(22, 22, 6, 6);

    black.backgroundColor = [UIColor redColor].CGColor;

    black.cornerRadius = 3;

    

    UIView *kanoko = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

    [self.view addSubview:kanoko];

    [kanoko.layer addSublayer:sl];

    [kanoko.layer addSublayer:black];

    

    return kanoko;

}

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

{

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

    self.mask.position = p;

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end