在最近做的自定義 PageControl——KYAnimatedPageControl 裡,我實現了 CALayer 的形變動畫與彈性動畫。效果先過目:

先列個提綱:
第一個主題是「如何讓 CALayer 發生形變」。這個技術我在之前的項目 KYCuteView 裡就用過,也寫過一篇簡短的實現原理文章,今天再舉一個例子。
第二個主題是「如何用阻尼震動函數生成 60 個關鍵幀」。我之前做過類似果凍效果的彈性動畫,比如 KYGooeyMenu,核心技術是 CAKeyframeAnimation 加幾個手動計算的關鍵幀,能初步達到彈性效果。但畢竟只有幾個關鍵幀、全靠手算,既不精確,動畫也不夠細膩——你不可能手動造 60 個關鍵幀。所以這次要做的,是用阻尼震動函數生成關鍵幀,實現類似 [UIView animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:] 那樣的彈性動畫。
正文開始。
關鍵技術其實很簡單:你需要用多條貝塞爾曲線「拼」出這個 Layer。原因不言而喻——這樣才方便形變。
比如 KYAnimatedPageControl 裡那個小球,它是這麼畫出來的:

小球由弧 AB、弧 BC、弧 CD、弧 DA 四段組成,每段弧綁定兩個控制點:弧 AB 綁定 C1、C2;弧 BC 綁定 C3、C4……
如何表達各個點?
首先,A、B、C、D 是四個動點,驅動它們的變量是 ScrollView 的 contentOffset.x。我們可以在 -(void)scrollViewDidScroll: 裡實時拿到這個值,並把它換算成一個 0~1 的系數,取名 factor:
_factor = MIN(1, MAX(0, (ABS(scrollView.contentOffset.x - self.lastContentOffset) / scrollView.frame.size.width)));
假設 A、B、C、D 的最大變化距離為小球直徑的 2/5。結合這個 0~1 的系數,真實變化距離 extra = (self.width * 2 / 5) * factor。當 factor == 1 時達到最大形變狀態,此時四個點的變化距離均為 (self.width * 2 / 5)。
注意:還要根據滑動方向判斷是 B 點動還是 D 點動。
CGPoint pointA = CGPointMake(rectCenter.x, self.currentRect.origin.y + extra);
CGPoint pointB = CGPointMake(self.scrollDirection == ScrollDirectionLeft
? rectCenter.x + self.currentRect.size.width / 2
: rectCenter.x + self.currentRect.size.width / 2 + extra * 2,
rectCenter.y);
CGPoint pointC = CGPointMake(rectCenter.x, rectCenter.y + self.currentRect.size.height / 2 - extra);
CGPoint pointD = CGPointMake(self.scrollDirection == ScrollDirectionLeft
? self.currentRect.origin.x - extra * 2
: self.currentRect.origin.x,
rectCenter.y);然後是控制點。關鍵是知道圖中 A-C1、B-C2、B-C3、C-C4…… 這些水平與垂直虛線的長度,命名為 offset。經過多次嘗試,我的結論是:當 offset 設為「直徑除以 3.6」時,弧線能完美貼合成圓弧。隱隱覺得這個 3.6 有必然性,似乎和 360 度存在某種關聯,也許通過推算能得出它的由來,但我沒有深究。
因此各控制點坐標為:
CGPoint c1 = CGPointMake(pointA.x + offset, pointA.y); CGPoint c2 = CGPointMake(pointB.x, pointB.y - offset); CGPoint c3 = CGPointMake(pointB.x, pointB.y + offset); CGPoint c4 = CGPointMake(pointC.x + offset, pointC.y); CGPoint c5 = CGPointMake(pointC.x - offset, pointC.y); CGPoint c6 = CGPointMake(pointD.x, pointD.y + offset); CGPoint c7 = CGPointMake(pointD.x, pointD.y - offset); CGPoint c8 = CGPointMake(pointA.x - offset, pointA.y);
有了端點和控制點,就可以用 UIBezierPath 的 - (void)addCurveToPoint:controlPoint1:controlPoint2: 畫線段了。
重寫 CALayer 的 - (void)drawInContext: 方法,在裡面畫圖形:
- (void)drawInContext:(CGContextRef)ctx {
.... // 在這裡計算每個點的坐標
UIBezierPath *ovalPath = [UIBezierPath bezierPath];
[ovalPath moveToPoint:pointA];
[ovalPath addCurveToPoint:pointB controlPoint1:c1 controlPoint2:c2];
[ovalPath addCurveToPoint:pointC controlPoint1:c3 controlPoint2:c4];
[ovalPath addCurveToPoint:pointD controlPoint1:c5 controlPoint2:c6];
[ovalPath addCurveToPoint:pointA controlPoint1:c7 controlPoint2:c8];
[ovalPath closePath];
CGContextAddPath(ctx, ovalPath.CGPath);
CGContextSetFillColorWithColor(ctx, self.indicatorColor.CGColor);
CGContextFillPath(ctx);
}現在,滑動 ScrollView 時小球就會隨之形變了。
上面的例子裡有個至關重要的因素:ScrollView 的 contentOffset.x。沒有這個輸入,後面什麼都不會發生。但這個變量需要用戶觸摸、滑動來產生。而有些動畫並沒有直接的交互輸入——比如手指離開之後,要讓小球以果凍效果彈回初始狀態,這時手指已經離開屏幕,也就沒有輸入,上面的方法自然行不通。所以我們需要 CAAnimation。
我們知道,iOS 7 中蘋果在 UIView(UIViewAnimationWithBlocks) 裡加入了一個製作彈性動畫的工廠方法:
+ (void)animateWithDuration:(NSTimeInterval)duration
delay:(NSTimeInterval)delay
usingSpringWithDamping:(CGFloat)dampingRatio
initialSpringVelocity:(CGFloat)velocity
options:(UIViewAnimationOptions)options
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion
NS_AVAILABLE_IOS(7_0);但並沒有對應的 CAAnimation 子類(類似 CABasicAnimation 或 CAKeyframeAnimation)可以直接給 CALayer 加彈性動畫。好消息是 iOS 9 提供了公開的 CASpringAnimation;不過出於兼容低版本以及求知的角度,我們還是可以了解一下如何手動給 CALayer 造一個彈性動畫。
開始之前,先復習一點高中物理——阻尼震動(可以點擊鏈接稍作回顧)。


根據維基百科,我們可以得到如下震動函數通式:

這只是通式,我們需要讓圖像過 (0, 0),並最終衰減到 1。做法是:先把原圖像繞 X 軸翻轉 180 度(也就是加一個負號),再沿 y 軸向上平移一個單位。稍加變形可得:

想看函數圖像?推薦一個在線繪圖網站 Desmos,把這段公式 1-\left(e^{-5x}\cdot \cos (30x)\right) 粘進去就能看到圖像。
改進後的函數圖像如下:

完美滿足「圖形過 (0, 0)、震蕩衰減到 1」的要求。其中式子裡的 5 相當於阻尼系數,數值越小幅度越大;30 相當於震蕩頻率,數值越大震蕩次數越多。
接下來轉成代碼。總體思路是創建 60 幀關鍵幀(因為屏幕最高刷新頻率就是 60FPS),再把這 60 組數據賦值給 CAKeyframeAnimation 的 values 屬性。
用下面的代碼生成 60 幀並返回數組,其中 //1 就是利用剛才的公式計算數值:
+ (NSMutableArray *)animationValues:(id)fromValue
toValue:(id)toValue
usingSpringWithDamping:(CGFloat)damping
initialSpringVelocity:(CGFloat)velocity
duration:(CGFloat)duration {
// 60 個關鍵幀
NSInteger numOfPoints = duration * 60;
NSMutableArray *values = [NSMutableArray arrayWithCapacity:numOfPoints];
for (NSInteger i = 0; i < numOfPoints; i++) {
[values addObject:@(0.0)];
}
// 差值
CGFloat d_value = [toValue floatValue] - [fromValue floatValue];
for (NSInteger point = 0; point < numOfPoints; point++) {
CGFloat x = (CGFloat)point / (CGFloat)numOfPoints;
// 1: y = 1 - e^{-5x} * cos(30x)
CGFloat value = [toValue floatValue] - d_value * (pow(M_E, -damping * x) * cos(velocity * x));
values[point] = @(value);
}
return values;
}接著創建一個對外的類方法,返回一個 CAKeyframeAnimation:
+ (CAKeyframeAnimation *)createSpring:(NSString *)keypath
duration:(CFTimeInterval)duration
usingSpringWithDamping:(CGFloat)damping
initialSpringVelocity:(CGFloat)velocity
fromValue:(id)fromValue
toValue:(id)toValue {
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:keypath];
NSMutableArray *values =
[KYSpringLayerAnimation animationValues:fromValue
toValue:toValue
usingSpringWithDamping:damping * dampingFactor
initialSpringVelocity:velocity * velocityFactor
duration:duration];
anim.values = values;
anim.duration = duration;
return anim;
}另一個關鍵
以上我們創建了 CAKeyframeAnimation。但這些 values 究竟是對誰生效的?如果你熟悉 Core Animation,答案很明確:對傳入的 keypath 生效。而這些 keypath 本質上就是 CALayer 的 @property。比如傳入 transform.rotation.x 時動畫會讓 layer 旋轉,就是因為 CAKeyframeAnimation 發現 CALayer 上有 transform 這個屬性。
現在我們要改變的是主題一裡那個 factor 變量。很自然地想到:給 CALayer 補一個名為 factor 的屬性就行。這樣當 CAKeyframeAnimation 加到 layer 上時,發現 layer 有 factor,就會把 60 幀不同的 values 逐幀賦給它。當然,要把 fromValue 和 toValue 控制在 0~1:
CAKeyframeAnimation *anim =
[KYSpringLayerAnimation createSpring:@"factor"
duration:0.8
usingSpringWithDamping:0.5
initialSpringVelocity:3
fromValue:@(1)
toValue:@(0)];
self.factor = 0;
[self addAnimation:anim forKey:@"restoreAnimation"];最後一步:雖然 CAKeyframeAnimation 實時改變了我們想要的 factor,但還得通知屏幕刷新,才能看到動畫:
+ (BOOL)needsDisplayForKey:(NSString *)key {
if ([key isEqual:@"factor"]) {
return YES;
}
return [super needsDisplayForKey:key];
}這段代碼告訴系統:factor 變化時實時刷新屏幕。
最後的最後,你需要重寫 CALayer 的 -(id)initWithLayer: 方法。為了保證動畫連貫,需要拷貝前一個狀態的 layer 及其所有屬性:
- (id)initWithLayer:(GooeyCircle *)layer {
self = [super initWithLayer:layer];
if (self) {
self.indicatorSize = layer.indicatorSize;
self.indicatorColor = layer.indicatorColor;
self.currentRect = layer.currentRect;
self.lastContentOffset = layer.lastContentOffset;
self.scrollDirection = layer.scrollDirection;
self.factor = layer.factor;
}
return self;
}總結:
做自定義動畫,最關鍵的是要有變量、要有輸入。滑動 ScrollView 時,滑動距離就是動畫的輸入,可以直接當變量用;沒有交互輸入時,則可以借助 CAAnimation。其實 CAAnimation 底層本身就有一個定時器,而定時器的作用就是持續產生變量——時間就是變量,於是就有了連續變化的輸入,也就有了連續變化的狀態,把它們連起來,就是動畫。