
轉自標哥的技術博客,作者:黃儀標(微博)
前段時間幫人做了一個動畫效果,今天分享出來。關於動畫基礎知識這裡不再贅述,若你還不具體核心動畫基礎,建議先了解 CAAnimation 的用法再回來閱讀本文。
本文涉及的知識點包括:縮放、平移、旋轉、關鍵幀動畫,組合動畫的使用,漸變圖層,以及圓形漸變進度條的實現。友情提示:新手可先掃一遍了解思路,但不必深究細節。
最終效果
無縮放動畫的版本:

可以看到其中包含平移、旋轉、關鍵幀動畫,以及漸變進度條填充的效果,同時要注意移動的距離。
有縮放動畫的版本:

相比上一版,它把中間的控件「分裂」成了 6 個並平均分布,多了縮放動畫(GIF 呈現的畫質較渣,實機效果要細膩得多)。
設計思路
這裡封裝了通用組件,便於項目中復用。整體由兩部分構成:中間帶進度圖的圓形控件(下文稱「葉子」),以及從中心散開到四周、特性一致的 N 個子控件。因此設計為三個類:
設計 HYBCurveItemView
每個「葉子」都需要知道:自身大小、展示元素、可移動到的最遠與最近位置、起始位置,以及最終展開後停留的位置。可設置以下位置屬性:
@property (nonatomic, assign) CGPoint startPoint; @property (nonatomic, assign) CGPoint endPoint; @property (nonatomic, assign) CGPoint nearPoint; @property (nonatomic, assign) CGPoint farPoint;
設計 HYBCurveMainView
「大圓」需要具備:自身大小、展示元素、漸變圓形進度條;可執行的操作包括更新進度、展開/收起葉子。下面重點講解圓形進度條的實現。
設計漸變進度圓環
首先添加白色固定圓形。底部是一個白色圓環,填滿時代表 0%。用 CAShapeLayer 添加圓形路徑即可實現(記得把填充色設為透明,否則會遮住中間內容):
self.outLayer = [CAShapeLayer layer];
CGRect rect = {kLineWidth / 2, kLineWidth / 2, frame.size.width - kLineWidth, frame.size.height - kLineWidth};
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
self.outLayer.strokeColor = [UIColor whiteColor].CGColor;
self.outLayer.lineWidth = kLineWidth;
self.outLayer.fillColor = [UIColor clearColor].CGColor;
self.outLayer.lineCap = kCALineCapRound;
self.outLayer.path = path.CGPath;
[self.layer addSublayer:self.outLayer];把畫筆設為白色、線寬設為圓環大小,便形成了白色底色,此時即 0%。
其次,創建可調進度的進度圓環圖層。它會作為漸變圖層的 mask,只顯示中間內容而非整片漸變,大小與白底圓環一致:
self.progressLayer = [CAShapeLayer layer]; self.progressLayer.frame = self.bounds; self.progressLayer.fillColor = [UIColor clearColor].CGColor; self.progressLayer.strokeColor = [UIColor whiteColor].CGColor; self.progressLayer.lineWidth = kLineWidth; self.progressLayer.lineCap = kCALineCapRound; self.progressLayer.path = path.CGPath;
然後增加漸變圖層。用 CAGradientLayer 創建,這裡用了兩個小漸變圖層各佔一半,再放進一個大漸變圖層;加上 mask 後,就只有進度這一段漸變可見:
CAGradientLayer *gradientLayer1 = [CAGradientLayer layer]; gradientLayer1.frame = CGRectMake(0, 0, width / 2, height); CGColorRef red = [UIColor redColor].CGColor; CGColorRef purple = [UIColor purpleColor].CGColor; CGColorRef yellow = [UIColor yellowColor].CGColor; CGColorRef orange = [UIColor orangeColor].CGColor; [gradientLayer1 setColors:@[(__bridge id)red, (__bridge id)purple, (__bridge id)yellow, (__bridge id)orange]]; [gradientLayer1 setLocations:@[@0.3, @0.6, @0.8, @1.0]]; [gradientLayer1 setStartPoint:CGPointMake(0.5, 1)]; [gradientLayer1 setEndPoint:CGPointMake(0.5, 0)]; CAGradientLayer *gradientLayer2 = [CAGradientLayer layer]; gradientLayer2.frame = CGRectMake(width / 2, 0, width / 2, height); CGColorRef blue = [UIColor brownColor].CGColor; CGColorRef purple1 = [UIColor purpleColor].CGColor; CGColorRef r1 = [UIColor yellowColor].CGColor; CGColorRef o1 = [UIColor orangeColor].CGColor; [gradientLayer2 setColors:@[(__bridge id)blue, (__bridge id)purple1, (__bridge id)r1, (__bridge id)o1]]; [gradientLayer2 setLocations:@[@0.3, @0.6, @0.8, @1.0]]; [gradientLayer2 setStartPoint:CGPointMake(0.5, 0)]; [gradientLayer2 setEndPoint:CGPointMake(0.5, 1)]; CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = self.bounds; [gradientLayer addSublayer:gradientLayer1]; [gradientLayer1 addSublayer:gradientLayer2]; gradientLayer.mask = self.progressLayer; [self.layer addSublayer:gradientLayer];
注意:一定要設置 gradientLayer.mask = self.progressLayer,否則只會看到一整片漸變而沒有中間內容。
最後,動畫更新進度。調用下面的方法即可帶動畫地更新進度:
- (void)updateProgressWithNumber:(NSUInteger)number {
[CATransaction begin];
[CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[CATransaction setAnimationDuration:0.5];
self.progressLayer.strokeEnd = number / 100.0;
self.percentLabel.text = [NSString stringWithFormat:@"%@%%", @(number)];
[CATransaction commit];
}設計 HYBCurveMenuView
這個圓形菜單類整合了前兩個類,需具備:自身大小、是否添加縮放動畫、更換葉子;可執行:展開/收起、點擊大圓回調、更換葉子。更換所有葉子時,需重新調整它們的位置:
- (void)setMenuItems:(NSArray *)menuItems {
if (_menuItems != menuItems) {
_menuItems = menuItems;
for (UIView *v in self.subviews) {
if (v.tag >= 1000) {
[v removeFromSuperview];
}
}
int count = (int)[menuItems count];
CGFloat cnt = 1;
for (int i = 0; i < count; i++) {
HYBCurveItemView *item = [menuItems objectAtIndex:i];
item.tag = 1000 + i;
item.startPoint = self.startPoint;
CGFloat pi = M_PI / count;
CGFloat endRadius = item.bounds.size.width / 2 + self.endDistance + _mainView.bounds.size.width / 2;
CGFloat nearRadius = item.bounds.size.width / 2 + self.nearDistance + _mainView.bounds.size.width / 2;
CGFloat farRadius = item.bounds.size.width / 2 + self.farDistance + _mainView.bounds.size.width / 2;
item.endPoint = CGPointMake(self.startPoint.x + endRadius * sinf(pi * cnt), self.startPoint.y - endRadius * cosf(pi * cnt));
item.nearPoint = CGPointMake(self.startPoint.x + nearRadius * sinf(pi * cnt), self.startPoint.y - nearRadius * cosf(pi * cnt));
item.farPoint = CGPointMake(self.startPoint.x + farRadius * sinf(pi * cnt), self.startPoint.y - farRadius * cosf(pi * cnt));
item.center = item.startPoint;
[self addSubview:item];
cnt += 2;
}
[self bringSubviewToFront:_mainView];
}
}其中幾個屬性帶有默認值(分別表示起點、最近點、最遠點、展開後最終停留點):
self.startPoint = self.center; self.nearDistance = 30; self.farDistance = 60; self.endDistance = 30;
上面各點的計算只用到一點點三角知識——掌握象限與角度的關係即可。
展開或收起
調用下面的方法展開或收起。它會遍歷所有葉子,為每個葉子添加對應的動畫變換,就能看到運動軌跡:
- (void)expend:(BOOL)isExpend {
_isExpend = isExpend;
[self.menuItems enumerateObjectsUsingBlock:^(HYBCurveItemView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (self.scale) {
if (isExpend) {
obj.transform = CGAffineTransformIdentity;
} else {
obj.transform = CGAffineTransformMakeScale(0.001, 0.001);
}
}
[self addRotateAndPostisionForItem:obj toShow:isExpend];
}];
}接下來是最關鍵的動畫核心(展開分支):
- (void)addRotateAndPostisionForItem:(HYBCurveItemView *)item toShow:(BOOL)show {
if (show) {
CABasicAnimation *scaleAnimation = nil;
if (self.scale) {
scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:0.2];
scaleAnimation.toValue = [NSNumber numberWithFloat:1.0];
scaleAnimation.duration = 0.5f;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
}
CAKeyframeAnimation *rotateAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
rotateAnimation.values = @[@(M_PI), @(0.0)];
rotateAnimation.duration = 0.5f;
rotateAnimation.keyTimes = @[@(0.3), @(0.4)];
CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
positionAnimation.duration = 0.5f;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, item.startPoint.x, item.startPoint.y);
CGPathAddLineToPoint(path, NULL, item.farPoint.x, item.farPoint.y);
CGPathAddLineToPoint(path, NULL, item.nearPoint.x, item.nearPoint.y);
CGPathAddLineToPoint(path, NULL, item.endPoint.x, item.endPoint.y);
positionAnimation.path = path;
CGPathRelease(path);
CAAnimationGroup *animationgroup = [CAAnimationGroup animation];
if (self.scale) {
animationgroup.animations = @[scaleAnimation, positionAnimation, rotateAnimation];
} else {
animationgroup.animations = @[positionAnimation, rotateAnimation];
}
animationgroup.duration = 0.5f;
animationgroup.fillMode = kCAFillModeForwards;
animationgroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[item.layer addAnimation:animationgroup forKey:@"Expand"];
item.center = item.endPoint;
} else {
// 收起:邏輯與展開類似,只是路徑改為 endPoint -> farPoint -> startPoint,縮放由大變小
...
[item.layer addAnimation:animationgroup forKey:@"Close"];
item.center = item.startPoint;
}
}展開縮放動畫:通過修改 transform.scale 實現 x、y 雙向縮放,剛出現時由小變大:
scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; scaleAnimation.fromValue = [NSNumber numberWithFloat:0.2]; scaleAnimation.toValue = [NSNumber numberWithFloat:1.0];
展開旋轉動畫:繞 z 軸旋轉(transform.rotation.z),用關鍵幀實現,values 與 keyTimes 個數需一一對應:
CAKeyframeAnimation *rotateAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"]; rotateAnimation.values = @[@(M_PI), @(0.0)]; rotateAnimation.duration = 0.5f; rotateAnimation.keyTimes = @[@(0.3), @(0.4)];
展開移動動畫:通過 position 配合路徑實現平移,路徑依次經過起點、最近、最遠、最終停留點:
CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; positionAnimation.duration = 0.5f; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, item.startPoint.x, item.startPoint.y); CGPathAddLineToPoint(path, NULL, item.farPoint.x, item.farPoint.y); CGPathAddLineToPoint(path, NULL, item.nearPoint.x, item.nearPoint.y); CGPathAddLineToPoint(path, NULL, item.endPoint.x, item.endPoint.y); positionAnimation.path = path; CGPathRelease(path);
展開組合動畫:把上述動畫用 CAAnimationGroup 組合起來,再添加到葉子上:
CAAnimationGroup *animationgroup = [CAAnimationGroup animation];
if (self.scale) {
animationgroup.animations = @[scaleAnimation, positionAnimation, rotateAnimation];
} else {
animationgroup.animations = @[positionAnimation, rotateAnimation];
}
animationgroup.duration = 0.5f;
animationgroup.fillMode = kCAFillModeForwards;
animationgroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[item.layer addAnimation:animationgroup forKey:@"Expand"];
item.center = item.endPoint;收起的動畫原理相同,不再贅述。
結尾
本文旨在教大家如何設計一個動畫與 UI 控件,筆者的做法未必最佳,你也許能想到更簡潔的方案。源碼不予放出,只給出關鍵代碼——對愛鑽研、學習能力強的朋友來說,這些已經足夠了。