有人希望做一個類似 QQ 賬號信息頁裡的弧形切換動畫,看著不難就開始動手,結果卡在數學上折騰了大半天。這個案例的難點不在 API,而在於怎麼把圓弧的幾何關係算清楚。
先看效果:

涉及的知識點:
(1) 三角函數
(2) CALayer
(3) CATransaction
(4) UIBezierPath
(5) CAKeyframeAnimation
(6) CAAnimationGroup

如圖,這是一段圓弧。要畫出來就得知道圓心和圓心角。這裡把圓心定在手機屏幕左上角(0, 0),圓心角取 60°,寬度記為 ScreenWidth,則半徑 R = ScreenWidth / cos(60°)。具體數值是反覆試出來的。
// 屏幕的寬度 CGFloat width = [UIScreen mainScreen].bounds.size.width; // 圓半徑 float r = 2 * width / sqrt(3); // 畫曲線 UIColor *color = [UIColor redColor]; [color set]; UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:r startAngle:M_PI / 2 endAngle:M_PI / 6 clockwise:NO]; path.lineWidth = 1.0; path.lineCapStyle = kCGLineCapRound; path.lineJoinStyle = kCGLineJoinRound; [path stroke];
A、B、C、D 四點分別作為四張圖片的圓心。兩端弧 SA 與 DE 各佔 7.5°,中間三段弧均分剩下的角度,即 (60 - 7.5 × 2) / 3 = 15°。於是 A 點坐標為(R·sin7.5°,R·cos7.5°),B、C、D 依次為(R·sin22.5°,R·cos22.5°)、(R·sin37.5°,R·cos37.5°)、(R·sin52.5°,R·cos52.5°)。
// 放圖片 for (int i = 0; i < 4; i++) { // 一共四個按鈕 從左到右index分別為0,1,2,3 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = [self getButtonFrame:i]; button.tag = i + 1; [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d",i + 1]] forState:UIControlStateNormal]; // 設置按鈕為圓 button.layer.cornerRadius = 25; button.layer.borderColor = [UIColor greenColor].CGColor; button.layer.masksToBounds = YES; button.layer.borderWidth = 2.0f; [self addSubview:button]; } // 根據Index確定按鈕的坐標 - (CGRect)getButtonFrame: (int) index { float radians = M_PI * (7.5 + 15 * index) / 180; CGFloat width = [UIScreen mainScreen].bounds.size.width; float r = 2 * width / sqrt(3); CGRect frame = CGRectMake(sin(radians) * r, cos(radians) * r, 50, 50); frame.origin.x = frame.origin.x - 25; frame.origin.y = frame.origin.y - 25; return frame; }
注意 frame 要往左上各偏移 25(半個寬高),讓坐標落在按鈕中心而非左上角。
self.head = [[UIImageView alloc] initWithFrame:[self getButtonFrame:0]]; self.head.image = [UIImage imageNamed:@"myHead"]; self.head.layer.borderColor = [UIColor greenColor].CGColor; self.head.layer.masksToBounds = YES; self.head.layer.cornerRadius = 25; self.head.layer.borderWidth = 2.0f; [self addSubview:self.head];
// 按鈕點擊事件 - (void)buttonClick:(UIButton *)button { // 原來圖片所在按鈕的index int preIndex = [self getPreviousIndexByFrame:self.head.frame]; int buttonIndex = (int)button.tag - 1; // 點擊圖片所在按鈕 不做任何操作 if (preIndex == buttonIndex) { return; } CGFloat width = [UIScreen mainScreen].bounds.size.width; float r = 2 * width / sqrt(3); //加入動畫效果 CALayer *transitionLayer = [[CALayer alloc] init]; //顯式事務默認開啟動畫效果,kCFBooleanTrue關閉 保證begin和commit 之間的屬性修改同時進行 transitionLayer.contents = self.head.layer.contents; transitionLayer.borderColor = [UIColor greenColor].CGColor; transitionLayer.masksToBounds = YES; transitionLayer.cornerRadius = 25; transitionLayer.borderWidth = 2.0f; transitionLayer.frame = self.head.frame; transitionLayer.backgroundColor=[UIColor blueColor].CGColor; [self.layer addSublayer:transitionLayer]; self.head.hidden = YES; UIBezierPath *movePath; //路徑曲線 貝塞爾曲線 if (buttonIndex > preIndex) { // 向上滑 逆時針 movePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:r startAngle:[self getAnticlockwiseByIndex:preIndex] endAngle:[self getAnticlockwiseByIndex:buttonIndex] clockwise:NO]; [movePath moveToPoint:transitionLayer.position]; }else { // 向下滑 順時針 movePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:r startAngle:[self getClockwiseAngleByIndex:preIndex] endAngle:[self getClockwiseAngleByIndex:buttonIndex] clockwise:YES]; [movePath moveToPoint:transitionLayer.position]; } //關鍵幀動畫效果 CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; // 動畫軌跡 positionAnimation.path = movePath.CGPath; // 動畫完成之後是否刪除動畫效果 positionAnimation.removedOnCompletion = NO; // 設置開始的時間 positionAnimation.beginTime = CACurrentMediaTime(); CGFloat time = 0.7; if (labs(buttonIndex - preIndex) > 1) { time = 0.4 * labs(buttonIndex - preIndex); } //動畫總時間 positionAnimation.duration = time; // 動畫的方式 淡入淡出 positionAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; // 執行完之後保存最新的狀態 positionAnimation.fillMode = kCAFillModeForwards; // 動畫完成之後,是否回到原來的地方 positionAnimation.autoreverses= NO; [transitionLayer addAnimation:positionAnimation forKey:@"opacity"]; [CATransaction setCompletionBlock:^{ [NSThread sleepForTimeInterval:time]; self.head.hidden = NO; self.head.frame = button.frame; [transitionLayer removeFromSuperlayer]; }]; } // 根據Index獲得順時針的弧度 - (float)getAnticlockwiseByIndex: (NSInteger)index { return M_PI * (0.5 - (7.5 + 15 * index) / 180); } // 根據Index獲得逆時針的弧度 - (float)getClockwiseAngleByIndex: (NSInteger)index { index = 3 - index; return M_PI * (30 + 7.5 + 15 * index) / 180; }
這裡的處理思路值得借鑑:真正參與移動的是一個臨時 CALayer,用 CAKeyframeAnimation 沿貝塞爾弧線運動,動畫結束後在 CATransaction 的完成回調裡把真實 head 挪到目標位置並移除臨時 layer。動畫時長還按跨越的格數做了動態計算,跨得越遠耗時越長,手感更自然。
整體難點其實就兩個:四個按鈕的坐標和圓弧半徑。數學撿回來之後,實現並不複雜。
以上就是這個弧形切換動畫的完整實現過程。