タッチでイチゴ柄の画面を作るiPhoneアプリのサンプルコードを描いてみよう。
#import “ViewController.h”
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
}
– (UIView *)createStrawberry
{
UIView *strawberry = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
strawberry.layer.anchorPoint = CGPointMake(0, 0);
UIBezierPath *path = [UIBezierPath bezierPath];
float r = 20;
for (int i=0; i<3; i++) {
float x = r * cos(i * 2.0 * M_PI / 3.0);
float y = r * sin(i * 2.0 * M_PI / 3.0);
if (i == 0) [path moveToPoint:CGPointMake(x, y)];
else [path addLineToPoint:CGPointMake(x, y)];
}
[path closePath];
UIColor *red = [UIColor redColor];
CAShapeLayer *l = [CAShapeLayer layer];
l.path = path.CGPath;
l.strokeColor = red.CGColor;
l.fillColor = red.CGColor;
l.lineWidth = 20;
l.lineJoin = kCALineJoinRound;
l.lineCap = kCALineCapRound;
[strawberry.layer addSublayer:l];
for (int i=0; i<20; i++) {
CALayer *dot = [CALayer layer];
dot.frame = CGRectMake((i%5) * 10 – 20, (i/5) * 10 – 15, 3, 3);
dot.backgroundColor = [UIColor whiteColor].CGColor;
[l addSublayer:dot];
}
UIBezierPath *path2 = [UIBezierPath bezierPath];
float r1 = 8;
float r2 = 16;
for (int i=0; i<16; i++) {
float x = ((i%2) ? r1 : r2) * cos(i * M_PI / 8.0);
float y = ((i%2) ? r1 : r2) * sin(i * M_PI / 8.0);
if (i==0) [path2 moveToPoint:CGPointMake(x, y)];
else [path2 addLineToPoint:CGPointMake(x, y)];
}
[path2 closePath];
CAShapeLayer *gl = [CAShapeLayer layer];
gl.path = path2.CGPath;
gl.fillColor = [UIColor greenColor].CGColor;
gl.position = CGPointMake(10, –15);
[l addSublayer:gl];
return strawberry;
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
UIView *strawberry = [self createStrawberry];
strawberry.center = p;
[self.view addSubview:strawberry];
[UIView animateWithDuration:0.5 animations:^{
float angle = (arc4random() % 8) * M_PI / 4.0;
strawberry.transform = CGAffineTransformMakeRotation(angle);
}];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end