粒子動(dòng)畫
效果:隨機(jī)繪制一條路徑,點(diǎn)擊開始按鈕,粒子動(dòng)畫
實(shí)現(xiàn)思路
1.搞個(gè)畫板繪制路徑家制,自定義view
2.給自定義view添加pan手勢(shì),和創(chuàng)建復(fù)制圖層和圓形圖層泡一,只需要設(shè)置一次颤殴,在awakeFromNib方法中設(shè)置。
// 添加pan手勢(shì)
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];
// 創(chuàng)建復(fù)制圖層
CAReplicatorLayer *repLayer = [CAReplicatorLayer layer];
repLayer.frame = self.bounds;
[self.layer addSublayer:repLayer];
// 創(chuàng)建粒子圖層
CALayer *layer = [CALayer layer];
layer.cornerRadius = 5;
layer.frame = CGRectMake(-100, 10, 10, 10);
layer.backgroundColor = [UIColor whiteColor].CGColor;
[repLayer addSublayer:layer];
_dotLayer = layer;
3.因?yàn)楹诵膭?dòng)畫只能設(shè)置一個(gè)路徑鼻忠,因此只能創(chuàng)建一個(gè)路徑涵但,懶加載路徑。
- (UIBezierPath *)path
{
if (_path == nil) {
_path = [UIBezierPath bezierPath];
}
return _path;
}
4.在一開始拖動(dòng)的時(shí)候帖蔓,保存路徑起點(diǎn)矮瘟,設(shè)置路徑起點(diǎn),拖動(dòng)的時(shí)候每次添加線到某個(gè)點(diǎn)塑娇。
CGPoint curP = [pan locationInView:self];
if (pan.state == UIGestureRecognizerStateBegan) {
_startP = curP;
[self.path moveToPoint:_startP];
}
[self.path addLineToPoint:curP];
[self setNeedsDisplay];
5.路徑繪制好了澈侠,點(diǎn)擊開始按鈕的時(shí)候,添加動(dòng)畫到圖層
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.duration = 4;
anim.path = self.path.CGPath;
anim.repeatCount = MAXFLOAT;
[_dotLayer addAnimation:anim forKey:@"anim"];
anim.delegate = self;
6.復(fù)制圖層
repLayer.instanceCount = 20;
repLayer.instanceDelay = 4 / 20.0;
// 設(shè)置子層顏色
repLayer.instanceColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:1].CGColor;
// 設(shè)置子層顏色綠色通道偏移量
repLayer.instanceGreenOffset = -0.03;
7.重繪
清空路徑埋酬,重新繪制哨啃,移除圖層動(dòng)畫。
_path = nil;
[_dotLayer removeAnimationForKey:@"anim"];
[self setNeedsDisplay];