近いし行かないだろうなとか思っていたスカイツリーに田舎からきた親戚と行くことになった記念。タッチで7色の丸が動くiPhoneアプリを描いてみる。(行ってみたら結構楽しかった。)
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (strong, nonatomic) UIView *tree;
@property (strong, nonatomic) NSMutableArray *balls;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createTree];
[self createBalls];
}
– (void)createTree
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(68.0/2.0, 0)];
[path addLineToPoint:CGPointMake(68, 634.0)];
[path addLineToPoint:CGPointMake(0, 634.0)];
[path closePath];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.fillColor = [UIColor lightGrayColor].CGColor;
sl.path = path.CGPath;
self.tree = [[UIView alloc] initWithFrame:CGRectMake(126, 0, 634, 68)];
[self.tree.layer addSublayer:sl];
[self.view addSubview:self.tree];
}
– (void)createBalls
{
self.balls = [[NSMutableArray alloc] init];
for (int i=0; i<14; i++) {
float x = (arc4random() % 260) + 20.0;
float y = (arc4random() % 280) + 20;
UIView *ball = [[UIView alloc] initWithFrame:CGRectMake(x, y, 30, 30)];
ball.layer.cornerRadius = 15;
ball.backgroundColor = [self color:i%7];
ball.alpha = 0.8;
[self.view addSubview:ball];
[self.balls addObject:ball];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
for (int i=0; i<14; i++) {
float x = (arc4random() % 260) + 20.0;
float y = (arc4random() % 180) + 20;
UIView *ball = [self.balls objectAtIndex:i];
[UIView animateWithDuration:3.0 animations:^{
ball.center = CGPointMake(x, y);
}];
}
}
#define UIColorHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
– (UIColor*)color:(int)i
{
switch (i) {
case 0:
return UIColorHex(0x729f79);
case 1:
return UIColorHex(0xa9c464);
case 2:
return UIColorHex(0xe8df63);
case 3:
return UIColorHex(0xfdc45c);
case 4:
return UIColorHex(0xf88999);
case 5:
return UIColorHex(0xae5da9);
case 6:
return UIColorHex(0x73cfcf);
default:
break;
}
return nil;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end