風車を画面上に並べます。それを指でなぞると、くるくる回りだすようなiPhoneアプリを書いてみようと思います。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self layoutKazaguruma];
}
– (void)layoutKazaguruma
{
for (int i=0; i<4*7; i++) {
float x = (i % 4) * 80;
float y = (i / 4) * 80;
[self createKazaguruma:CGRectMake(x, y, 80, 80)];
}
}
– (UIView*)createKazaguruma:(CGRect)frame
{
UIView *kazaguruma = [[UIView alloc] initWithFrame:frame];
kazaguruma.tag = 1;
[self.view addSubview:kazaguruma];
for (int i=0; i<4; i++) {
CALayer *hane = [self createHane];
CATransform3D t = CATransform3DMakeTranslation(0, 40, 0);
hane.transform = CATransform3DRotate(t, i * M_PI/2.0, 0, 0, 1);
[kazaguruma.layer addSublayer:hane];
}
return kazaguruma;
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
UIView *v = [self.view hitTest:p withEvent:nil];
if (v.tag == 1 && [v.layer.animationKeys count] == 0) {
v.userInteractionEnabled = NO;
CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@”transform.rotation.z”];
a.toValue = @(2 * M_PI);
a.duration = 1.0;
a.repeatCount = 2;
[v.layer addAnimation:a forKey:@”turn”];
[v performSelector:@selector(setUserInteractionEnabled:) withObject:@YES afterDelay:2.0];
}
}
– (CALayer*)createHane
{
float size = 20;
float hue = (arc4random()%50)/50.0;
CALayer *l = [CALayer layer];
l.frame = CGRectMake(0, 0, size * 2, size);
l.anchorPoint = CGPointMake(1, 0);
l.position = CGPointMake(size*2, 0);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(size * 2, 0)];
[path addLineToPoint:CGPointMake(size, size)];
[path closePath];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.fillColor = [UIColor colorWithHue:hue saturation:0.5 brightness:1 alpha:1].CGColor;
sl.path = path.CGPath;
[l addSublayer:sl];
path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(size, size)];
[path addLineToPoint:CGPointMake(size * 2, 0)];
[path addLineToPoint:CGPointMake(size * 2, size)];
[path closePath];
sl = [CAShapeLayer layer];
sl.fillColor = [UIColor colorWithHue:hue saturation:1 brightness:0.9 alpha:1].CGColor;
sl.path = path.CGPath;
[l addSublayer:sl];
return l;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end