ひよこみたいなのが、線で囲んだ卵をかぞえるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@interface ViewController ()
@property (nonatomic, strong) UIBezierPath *path;
@property (nonatomic, weak) CAShapeLayer *sl;
@property (nonatomic, weak) UIImageView *bird;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
[self showEggs];
[self showBird];
}
– (void)showBird
{
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”bird”]];
[self.view addSubview:iv];
self.bird = iv;
}
– (void)showEggs
{
for (int i=0; i<30; i++) {
float x = arc4random() % 300 + 10;
float y = arc4random() % 300 + 100;
UIImageView *egg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”egg”]];
egg.tag = 1;
egg.center = CGPointMake(x, y);
[self.view addSubview:egg];
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
CAShapeLayer *l = [CAShapeLayer layer];
l.fillColor = [UIColor clearColor].CGColor;
l.strokeColor = [UIColor whiteColor].CGColor;
l.lineWidth = 5;
[self.view.layer insertSublayer:l atIndex:0];
self.sl = l;
self.bird.center = CGPointMake(p.x, p.y – 20);
self.path = [UIBezierPath bezierPath];
[self.path moveToPoint:p];
}
– (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint p = [[touches anyObject] locationInView:self.view];
self.bird.center = CGPointMake(p.x, p.y – 20);
[self.path addLineToPoint:p];
self.sl.path = self.path.CGPath;
}
– (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.sl.fillColor = [[UIColor brownColor] colorWithAlphaComponent:0.5].CGColor;
NSPredicate *pred = [NSPredicate predicateWithFormat:@”tag == %d”, 1];
__block NSUInteger count = 0;
[[self.view.subviews filteredArrayUsingPredicate:pred] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIImageView *egg = (UIImageView *)obj;
if ([self.path containsPoint:egg.center]) {
[UIView animateWithDuration:0.5 delay:0.1*count options:0 animations:^{
egg.transform = CGAffineTransformMakeTranslation(0, –500);
} completion:^(BOOL finished) {}];
count++;
}
}];
UILabel *l = [[UILabel alloc] init];
l.font = [UIFont fontWithName:@”chalkduster” size:40];
l.textColor = [UIColor brownColor];
l.text = [@(count) stringValue];
[l sizeToFit];
CGRect pathRect = CGPathGetPathBoundingBox(self.path.CGPath);
l.center = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));
[self.view addSubview:l];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end