画面をなぞって雪の結晶をふらせてあそんでみよう。と言う感じで、iPhoneアプリのサンプルコードを描いてみます。
動かすとこんな感じです
サンプルコード
#import “ViewController.h”
@interface SnowCrystal : UIView
@end
@implementation SnowCrystal
– (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setBackgroundColor:[UIColor clearColor]];
}
return self;
}
-(void)drawRect:(CGRect)rect
{
[[UIColor whiteColor] setStroke];
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextSetShadowWithColor(ref, CGSizeMake(1.0, 1.0), 10, [UIColor whiteColor].CGColor);
for (int i=0; i<6; i++) {
UIBezierPath *path = [self createPart];
[path applyTransform:[self rotateAroundCenter:i * M_PI / 3.0]];
[path stroke];
}
}
– (UIBezierPath*)createPart
{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds), 0)];
[path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))];
float size = CGRectGetMidX(self.bounds) * 0.20;
[path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds) – size, size)];
[path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds), 2.0 * size)];
[path addLineToPoint:CGPointMake(CGRectGetMidX(self.bounds) + size, size)];
[path setLineWidth:self.bounds.size.width * 0.05];
return path;
}
– (CGAffineTransform)rotateAroundCenter:(float)angle
{
CGAffineTransform t = CGAffineTransformIdentity;
t= CGAffineTransformTranslate(t, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
t = CGAffineTransformRotate(t, angle);
t = CGAffineTransformTranslate(t, –CGRectGetMidX(self.bounds), –CGRectGetMidY(self.bounds));
return t;
}
@end
@interface ViewController ()
@property CGPoint lastPoint;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p1 = [[touches anyObject] locationInView:self.view];
CGPoint p2 = self.lastPoint;
CGFloat distance = hypotf(p1.x – p2.x, p1.y – p2.y);
if (distance < 40) {
return;
}
self.lastPoint = p1;
float size = (arc4random() % 25) + 25;
SnowCrystal *crystal = [[SnowCrystal alloc] initWithFrame:CGRectMake(0, 0, size, size)];
crystal.center = p1;
[self.view addSubview:crystal];
float v = (arc4random() % 5) + 3.0;
[UIView animateWithDuration:20.0 / v animations:^{
crystal.center = CGPointMake(crystal.center.x, CGRectGetMaxY(self.view.bounds) + 50);
crystal.transform = CGAffineTransformMakeRotation(M_PI);
} completion:^(BOOL finished) {
[crystal removeFromSuperview];
}];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end