关键帧动画-五角星动画-在层上画出五角星
本例是对核心动画教程的 关键帧动画中的一个例子的一点总结与自己的心得
在.h文件中 定义一个 CGMutablePathRef starPath; 用来纪录当前的路径 以便于绘画。
.m文件
- (IBAction)action:(id)sender {
//创建五角星的路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,240.0, 280.0);
CGPathAddLineToPoint(path, NULL, 181.0, 99.0);
CGPathAddLineToPoint(path, NULL, 335.0, 210.0);
CGPathAddLineToPoint(path, NULL, 144.0, 210.0);
CGPathAddLineToPoint(path, NULL, 298.0, 99.0);
CGPathCloseSubpath(path);
//创建关键帧动画实例
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//关键帧动画定义为10秒,一共6帧,每一帧是10/(6-1)等与2秒
[animation setDuration:10.0f];
[animation setDelegate:self];
[animation setPath:path];
[self.block.layer addAnimation:animation forKey:NULL];
//在每一帧结束的时候 定时器进入其方法
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self
selector:@selector(legOne:) userInfo:nil
repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:4.0
target:self selector:@selector(legTwo:) userInfo:nil
repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:6.0 target:self
selector:@selector(legThree:) userInfo:nil repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:8.0 target:self selector:@selector(legFour:) userInfo:nil
repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(legFive:) userInfo:nil
repeats:NO];
// Tell the root layer to call drawLayer
//不设定这个Delegate 调用setNeedDisplay的时候 会不进入 drawLayer方法
[self.view.layer setDelegate:self];
}
注意最后一行代码的作用
- (void)legOne:(id)sender {
CGPathAddLineToPoint(starPath, NULL, 181.0, 99.0);
[self.view.layer setNeedsDisplay];
}
- (void)legTwo:(id)sender { CGPathAddLineToPoint(starPath, NULL, 335.0, 210.0);
[self.view.layer setNeedsDisplay];
}
- (void)legThree:(id)sender { CGPathAddLineToPoint(starPath, NULL, 144.0, 210.0);
[self.view.layer setNeedsDisplay];
}
- (void)legFour:(id)sender { CGPathAddLineToPoint(starPath, NULL, 298.0, 99.0);
[self.view.layer setNeedsDisplay];
}
- (void)legFive:(id)sender { CGPathCloseSubpath(starPath);
[self.view.layer setNeedsDisplay];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
CGColorRef white =[UIColor whiteColor].CGColor;
CGContextSetStrokeColorWithColor(context, white);
//CFRelease(white);
CGContextBeginPath(context);
CGContextAddPath(context, starPath);
CGContextSetLineWidth(context, 3.0);
CGContextStrokePath(context);
NSLog(@"im in drawLayer");
}
另外 注意 在.h文件中定义的 starPath 要初始化 在ViewDidLoad中完成的
starPath=CGPathCreateMutable();
CGPathMoveToPoint(starPath,NULL,240.0, 280.0);
浙公网安备 33010602011771号