一、顯示效果
顯示效果
二、原理分析
1、拆解動畫
從效果圖來看,動畫可拆解成兩部分:放大動畫
、位移動畫
放大動畫
比較簡單,這里主要來分析一下位移動畫
(1)、先去掉縮放效果:
屏蔽放大效果
(2)、去掉其中的一個圓球
這里寫圖片描述
現在基本可以看出主要原理就是讓其中一個圓球繞另一個球做圓弧運動
,只要確定一個圓球的運動軌跡,另一個圓球和它左相對運動即可。下面咱們重點說一下這個圓弧運動
的原理。
2、圓弧運動
為了方便觀察我們先放慢一下這個動畫,然后添加輔助線:
放慢后的效果圖
從圖中可以看出,藍色球主要經過了三段軌跡
第一段:從左邊緣逆時針運動180°到灰色球的右側
第二段:從灰色球右側貼著灰色球逆時針運動180°到其左側
第三段:從灰色球左側返回起始位置
既然分析出了運動軌跡,下面實現起來就方便了
第一段:藍色球以A為起點,沿圓心O逆時針運動到B點
第一段運動軌跡圖
第二段:藍色球以B為起點繞圓心P運動到C點
第二段運動軌跡圖
第三段:從C點返回原點
第三段運動軌跡圖
三、實現代碼
1、第一段運動:
確定起始點、圓心、半徑,讓藍色小球繞大圓
//動畫容器的寬度
CGFloat width = _ballContainer.bounds.size.width;
//小圓半徑
CGFloat r = (_ball1.bounds.size.width)*ballScale/2.0f;
//大圓半徑
CGFloat R = (width/2 + r)/2.0;
UIBezierPath *path1 = [UIBezierPath bezierPath];
//設置起始位置
[path1 moveToPoint:_ball1.center];
//畫大圓(第一段的運動軌跡)
[path1 addArcWithCenter:CGPointMake(R + r, width/2) radius:R startAngle:M_PI endAngle:M_PI*2 clockwise:NO];
2、第二段運動
以灰色小球中心為圓心,以其直徑為半徑繞小圓,并拼接兩段曲線
//畫小圓
UIBezierPath *path1_1 = [UIBezierPath bezierPath];
//圓心為灰色小球的中心 半徑為灰色小球的半徑
[path1_1 addArcWithCenter:CGPointMake(width/2, width/2) radius:r*2 startAngle:M_PI*2 endAngle:M_PI clockwise:NO];
[path1 appendPath:path1_1];
3、第三段運動
//回到原處
[path1 addLineToPoint:_ball1.center];
4、位移動畫
利用關鍵幀動畫實現小球沿設置好的貝塞爾曲線移動
//執行動畫
CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation1.path = path1.CGPath;
animation1.removedOnCompletion = YES;
animation1.duration = [self animationDuration];
animation1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[_ball1.layer addAnimation:animation1 forKey:@"animation1"];
5、縮放動畫
在每次位移動畫開始時執行縮放動畫
-(void)animationDidStart:(CAAnimation *)anim{
CGFloat delay = 0.3f;
CGFloat duration = [self animationDuration]/2 - delay;
[UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseOut| UIViewAnimationOptionBeginFromCurrentState animations:^{
_ball1.transform = CGAffineTransformMakeScale(ballScale, ballScale);
_ball2.transform = CGAffineTransformMakeScale(ballScale, ballScale);
_ball3.transform = CGAffineTransformMakeScale(ballScale, ballScale);
} completion:^(BOOL finished) {
[UIView animateWithDuration:duration delay:delay options:UIViewAnimationOptionCurveEaseInOut| UIViewAnimationOptionBeginFromCurrentState animations:^{
_ball1.transform = CGAffineTransformIdentity;
_ball2.transform = CGAffineTransformIdentity;
_ball3.transform = CGAffineTransformIdentity;
} completion:nil];
}];
}
6、動畫循環
在每次動畫結束時從新執行動畫
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
if (_stopAnimationByUser) {return;}
[self startPathAnimate];
}