編輯:關於 Android 程式設計
上一篇整理了 Core Animation 的基礎概念,這次則把重點放在實際應用,會用到 CAShapeLayer、CAReplicatorLayer 等圖層知識。
先看成果:
1、切換圖片

2、彩票轉盤

3、圖片折疊

4、進度條旋轉

5、粒子效果

看起來頗有份量的動畫,其實只需少量運算與程式碼就能完成,前提是對 Core Animation 與 Core Graphics 有一定理解。日常開發中若對底層總是「拿來就用、不求甚解」,能力很難累積;自己動手造過幾次輪子,經驗與思維才會真正長出來。
做法是組合三種動畫物件:CABasicAnimation 負責 view 的 zPosition 變化,CAKeyframeAnimation 負責位移與旋轉,最後一起放進 CAAnimationGroup 播放。表面上像兩張圖各有 independently 的表現,實際上呼叫的是同一個方法,只是平移方向與旋轉角度帶入不同參數。
這裡有個必須記住的觀念:Core Animation 產生的位移、旋轉、縮放都只是「視覺上的假象」,model layer 上的 view 並未真正改變。因此動畫結束後若不處理,畫面會跳回原樣。解法是在動畫開始時就把 view.layer.zPosition 設為終值——數值越大,在 z 軸上越靠前。
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSMutableArray *images; @property (nonatomic, assign) int currentIndex; @property (weak, nonatomic) IBOutlet UIImageView *currentImageView; @property (weak, nonatomic) IBOutlet UIImageView *behindImageView; @end @implementation ViewController - (NSMutableArray *)images { if (_images == nil) { _images = [NSMutableArray array]; for (int i = 1; i <= 7; i++) { UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"%d",i]]; [_images addObject:image]; } } return _images; } - (void)viewDidLoad { [super viewDidLoad]; self.currentIndex = 0; self.currentImageView.image = self.images[_currentIndex]; } - (void)addAnimateWithPoint:(CGPoint )point angle:(CGFloat)angle fromZ:(CGFloat)fromZ toZ:(CGFloat)toZ view:(UIView *)view { CABasicAnimation *zPosition = [[CABasicAnimation alloc] init]; zPosition.keyPath = @"zPosition"; zPosition.fromValue = @(fromZ); zPosition.toValue = @(toZ); zPosition.duration = 1.2; CAKeyframeAnimation *rotation = [[CAKeyframeAnimation alloc] init]; rotation.keyPath = @"transform.rotation"; rotation.values = @[@(0), @(angle), @(0)]; rotation.duration = 2; rotation.timingFunctions = @[ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; CAKeyframeAnimation *position = [[CAKeyframeAnimation alloc] init]; position.keyPath = @"position"; // CGPointMake(110, -20) position.values = @[ [NSValue valueWithCGPoint:CGPointZero], [NSValue valueWithCGPoint:point], [NSValue valueWithCGPoint:CGPointZero] ]; position.timingFunctions = @[ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut] ]; position.additive = YES; position.duration = 1.2; CAAnimationGroup *animateGroup = [[CAAnimationGroup alloc] init]; animateGroup.animations = @[zPosition, rotation, position]; // animateGroup.beginTime = 0.5; animateGroup.delegate = self; animateGroup.duration = 1.2; [animateGroup setValue:view forKey:@"view"]; [view.layer addAnimation:animateGroup forKey:nil]; view.layer.zPosition = toZ; } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { CAAnimationGroup *group = [anim valueForKey:@"view"]; if (group != nil) { self.currentImageView.image = self.images[_currentIndex]; self.currentImageView.layer.zPosition = 1; self.behindImageView.image = nil; self.behindImageView.layer.zPosition = -1; } } - (IBAction)previous:(id)sender { self.currentIndex = (self.currentIndex + 1) % self.images.count; self.behindImageView.image = self.images[_currentIndex]; [self addAnimateWithPoint:CGPointMake(-90, 20) angle:0.15 fromZ:-1 toZ:1 view:self.behindImageView]; [self addAnimateWithPoint:CGPointMake(90, -20) angle:-0.15 fromZ:1 toZ:-1 view:self.currentImageView]; } - (IBAction)next:(id)sender { self.currentIndex = (self.currentIndex + 6) % self.images.count; self.behindImageView.image = self.images[_currentIndex]; [self addAnimateWithPoint:CGPointMake(-90, 20) angle:-0.15 fromZ:-1 toZ:1 view:self.behindImageView]; [self addAnimateWithPoint:CGPointMake(90, -20) angle:0.15 fromZ:1 toZ:-1 view:self.currentImageView]; } @end
這個動畫的難點其實不在動畫本身,而在 12 個按鈕如何精準排成一個圓。做法是把每顆按鈕的 anchorPoint 設為 (0.5, 1),position 設為圓心,再用 transform 旋轉各自的角度,這樣一來所有按鈕就都繞著圓心均勻分布。
一般來說,控制項的 anchorPoint 就是中心點,所以旋轉、平移都是繞著中心在跑。但當「繞中心」的模型不敷使用時,CALayer 開放修改 anchorPoint 就成了強力工具,能實現許多看似複雜的動畫。
另一個細節是點擊熱區。扇形上寬下窄,若不處理,使用者點擊下方空白處可能選不到預期的按鈕。這裡自訂了一個 UIButton 子類,重寫 hitTest:withEvent: 來限定可響應的區域。
#import "ZYWheelView.h" #define ZYImageW 40 #define ZYImageH 46 @interface ZYButton : UIButton @end @implementation ZYButton /** * 重寫此方法,截取button的點擊 * */ - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { CGFloat btnW = self.bounds.size.width; CGFloat btnH = self.bounds.size.height; CGFloat x = 0; CGFloat y = btnH / 2; CGFloat w = btnW; CGFloat h = y; CGRect rect = CGRectMake(x, y, w, h); if (CGRectContainsPoint(rect, point)) { return nil; }else{ return [super hitTest:point withEvent:event]; } } - (CGRect)imageRectForContentRect:(CGRect)contentRect { CGFloat imageX = (contentRect.size.width - ZYImageW ) * 0.5; CGFloat imageY = 18; return CGRectMake(imageX, imageY, ZYImageW, ZYImageH); } - (void)setHighlighted:(BOOL)highlighted { } @end @interface ZYWheelView () @property (weak, nonatomic) IBOutlet UIImageView *wheelView; @property (nonatomic, weak) UIButton *lastSelectedBtn; @property (nonatomic, strong) CADisplayLink *timer; @end @implementation ZYWheelView + (instancetype)wheelView { return [[[NSBundle mainBundle] loadNibNamed:@"ZYWheelView" owner:nil options:nil] lastObject]; } - (void)awakeFromNib { self.wheelView.userInteractionEnabled = YES; CGFloat angle = 2 * M_PI / 12.0; UIImage *normalImage = [UIImage imageNamed:@"LuckyAstrology"]; UIImage *selectedImage = [UIImage imageNamed:@"LuckyAstrologyPressed"]; for (int bi = 0; bi < 12; bi++) { ZYButton *btn = [[ZYButton alloc] init]; [btn setBackgroundImage:[UIImage imageNamed:@"LuckyRototeSelected"] forState:UIControlStateSelected]; // 切割圖片,將切割好的圖片設置到按鈕上 // CGImage中rect是當做像素來使用 // UIKit 中是點坐標系 // 坐標系的特點:如果在非retain屏上 1個點等於1個像素 // 在retain屏上1個點等於2個像素 CGFloat imageH = ZYImageH * [UIScreen mainScreen].scale; CGFloat imageW = ZYImageW * [UIScreen mainScreen].scale; CGFloat imageY = 0; CGFloat imageX = bi * imageW; CGRect rect = CGRectMake(imageX, imageY, imageW, imageH); CGImageRef normalRef = CGImageCreateWithImageInRect(normalImage.CGImage, rect); CGImageRef selectedRef = CGImageCreateWithImageInRect(selectedImage.CGImage, rect); [btn setImage:[UIImage imageWithCGImage:normalRef] forState:UIControlStateNormal]; [btn setImage:[UIImage imageWithCGImage:selectedRef] forState:UIControlStateSelected]; btn.bounds = CGRectMake(0, 0, 58, 143); btn.layer.anchorPoint = CGPointMake(0.5, 1); btn.layer.position = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5); btn.transform = CGAffineTransformMakeRotation(angle * bi); [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside]; [self.wheelView addSubview:btn]; } [self startRotating]; } - (void)startRotating { if (self.timer) return; self.timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateTimer)]; [self.timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; } - (void)stopRotating { [self.timer invalidate]; self.timer = nil; } - (void)clickBtn:(UIButton *)btn { self.lastSelectedBtn.selected = NO; btn.selected = YES; self.lastSelectedBtn = btn; } - (IBAction)clickCenterBtn:(id)sender { self.userInteractionEnabled = NO; [self stopRotating]; CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; basicAnimation.toValue = @(M_PI * 2 * 5); basicAnimation.duration = 2; basicAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; // basicAnimation.removedOnCompletion = NO; // basicAnimation.fillMode = kCAFillModeForwards; basicAnimation.delegate = self; [self.wheelView.layer addAnimation:basicAnimation forKey:nil]; } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { self.userInteractionEnabled = YES; // 根據選中的按鈕獲取旋轉的度數, // 通過transform獲取角度 CGFloat angle = atan2(self.lastSelectedBtn.transform.b, self.lastSelectedBtn.transform.a); // 從實際上旋轉轉盤 self.wheelView.transform = CGAffineTransformMakeRotation(-angle); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self startRotating]; }); } - (void)updateTimer { self.wheelView.transform = CGAffineTransformRotate(self.wheelView.transform, M_PI / 200); } - (void)dealloc { [self stopRotating]; } @end
效果很吸睛,實作卻不難。需要三個 view:兩個 UIImageView 與一個承接拖拽手勢的容器。CALayer 有個 contentsRect 屬性,可用來設定圖層中實際顯示的範圍——這個屬性也很適合做「邊下載邊顯示」的漸進式載入。這裡用它讓兩張 ImageView 各顯示半張圖,再拼接成完整畫面,並在覆蓋層上掛 UIPanGestureRecognizer 驅動動畫。
另外引入一個新圖層 CAGradientLayer,專門處理漸層,用法與 CALayer 相近:
CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = self.bottomView.bounds; gradientLayer.opacity = 0; gradientLayer.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor]; self.gradientLayer = gradientLayer; [self.bottomView.layer addSublayer:gradientLayer]; // 設置漸變顏色 // gradientL.colors = @[(id)[UIColor redColor].CGColor,(id)[UIColor greenColor].CGColor,(id)[UIColor yellowColor].CGColor]; // 設置漸變定位點 // gradientL.locations = @[@0.1,@0.4,@0.5]; // 設置漸變開始點,取值0~1 // gradientL.startPoint = CGPointMake(0, 1);
設定好之後,只需在 pan 手勢的方法裡持續調整 gradientLayer 的 opacity,就能呈現折疊時的陰影漸深。
還有 CATransform3D 的 m34 屬性,用於設定透視強度,實務上常取 -1 / 500.0,可依視覺需求微調。
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *topView; @property (weak, nonatomic) IBOutlet UIImageView *bottomView; @property (weak, nonatomic) IBOutlet UIView *containView; @property (nonatomic, weak) CAGradientLayer *gradientLayer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self setupOtherView]; //設置漸變的陰影 [self setupShadow]; } - (void)setupOtherView { //設置contentsRect用來表示圖片顯示的大小,可以做邊下載邊顯示的UI效果,取值是(0--1) self.topView.layer.contentsRect = CGRectMake(0, 0, 1, 0.5); self.topView.layer.anchorPoint = CGPointMake(0.5, 1); self.bottomView.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5); self.bottomView.layer.anchorPoint = CGPointMake(0.5, 0); UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self.containView addGestureRecognizer:gesture]; } - (void)setupShadow { CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = self.bottomView.bounds; gradientLayer.opacity = 0; gradientLayer.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor]; self.gradientLayer = gradientLayer; [self.bottomView.layer addSublayer:gradientLayer]; // 設置漸變顏色 // gradientL.colors = @[(id)[UIColor redColor].CGColor,(id)[UIColor greenColor].CGColor,(id)[UIColor yellowColor].CGColor]; // 設置漸變定位點 // gradientL.locations = @[@0.1,@0.4,@0.5]; // 設置漸變開始點,取值0~1 // gradientL.startPoint = CGPointMake(0, 1); } - (void)pan:(UIPanGestureRecognizer *)recognizer { CGFloat y = [recognizer translationInView:self.containView].y; if (y >= 300) y = 300; if (y <= -300) y = -300; // 旋轉角度,往下逆時針旋轉 CGFloat angle = -y / 320.0 * M_PI; self.topView.layer.transform = CATransform3DIdentity; CATransform3D transfrom = CATransform3DIdentity; transfrom.m34 = -1 / 500.0; self.topView.layer.transform = CATransform3DRotate(transfrom, angle, 1, 0, 0); self.gradientLayer.opacity = y / 300.0; if (recognizer.state == UIGestureRecognizerStateEnded) { // 彈簧效果的動畫 // SpringWithDamping:彈性系數,越小,彈簧效果越明顯 [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:11 options:UIViewAnimationOptionCurveEaseInOut animations:^{ self.topView.layer.transform = CATransform3DIdentity; self.gradientLayer.opacity = 0; } completion:nil]; } } @end
轉圈圈的載入動畫最常出現在 HUD 上。早年我也做過類似效果,當時知識儲備不足,只能用 CAKeyframeAnimation:請美工做一張頂端帶小白點、其餘為 clearColor 的長條圖,設定 anchorPoint 後給它一條圓形 path 繞行。勉强能做,觀感卻不理想。
現在有更漂亮的解法——CAReplicatorLayer(複製圖層)。在複製圖層中加入一個 instance 圖層,並設定 instanceCount(例如 22),系統就會自動複製出 22 個相同圖層;由於動畫也會被複製,只需對 instance 圖層設定一次動畫即可。此外還能透過 instanceTransform 調整每個複副本的變換以完成環形排布,並用 instanceDelay 控制彼此間的啟動延遲,製造依序淡出的殘影感。
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIView *containView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self setupReplicatorLayerAndAnimation]; } - (void)setupReplicatorLayerAndAnimation { CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer]; replicatorLayer.frame = self.containView.layer.bounds; [self.containView.layer addSublayer:replicatorLayer]; CALayer *layer = [CALayer layer]; layer.frame = CGRectMake(self.containView.frame.size.width * 0.5, 20, 16, 16); layer.backgroundColor = [UIColor redColor].CGColor; layer.cornerRadius = layer.frame.size.width / 2; //這一句可以將初始過程移除掉 layer.transform = CATransform3DMakeScale(0, 0, 0); [replicatorLayer addSublayer:layer]; replicatorLayer.instanceCount = 22; CABasicAnimation *basicAn = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; basicAn.fromValue = @1; basicAn.toValue = @0; basicAn.duration = 1; basicAn.repeatCount = MAXFLOAT; [layer addAnimation:basicAn forKey:nil]; replicatorLayer.instanceDelay = basicAn.duration / (double)replicatorLayer.instanceCount; replicatorLayer.instanceTransform = CATransform3DMakeRotation(2 * M_PI / replicatorLayer.instanceCount, 0, 0, 1); } @end
這其實是 CAReplicatorLayer 與 Core Graphics 的組合技。用 UIBezierPath 描出手寫軌跡,把 path 交給 CAKeyframeAnimation 當作 position 的運動路徑,再將小球圖層放進複製圖層,設定 instanceCount 與 instanceDelay,沿著軌跡追跑的粒子流就出現了。
#import "ZYDrawView.h" @interface ZYDrawView () @property (nonatomic, strong) UIBezierPath *bezierPath; @property (nonatomic, weak) CAReplicatorLayer *replicatorLayer; @property (nonatomic, weak) CALayer *norLayer; @end static int _count = 0; @implementation ZYDrawView - (UIBezierPath *)bezierPath { if (_bezierPath == nil) { _bezierPath = [[UIBezierPath alloc] init]; } return _bezierPath; } - (void)awakeFromNib { CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer]; replicatorLayer.frame = self.bounds; [self.layer addSublayer:replicatorLayer]; CALayer *layer = [CALayer layer]; layer.frame = CGRectMake(0, -200, 10, 10); layer.cornerRadius = layer.frame.size.width * 0.5; layer.backgroundColor = [UIColor redColor].CGColor; [replicatorLayer addSublayer:layer]; self.replicatorLayer = replicatorLayer; self.norLayer = layer; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { CGPoint curPoint = [[touches anyObject] locationInView:self]; [self.bezierPath moveToPoint:curPoint]; } - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { _count++; CGPoint curPoint = [[touches anyObject] locationInView:self]; [self.bezierPath addLineToPoint:curPoint]; [self setNeedsDisplay]; } - (void)startAnimation { CAKeyframeAnimation *keyframeAn = [CAKeyframeAnimation animationWithKeyPath:@"position"]; keyframeAn.path = self.bezierPath.CGPath; keyframeAn.duration = 4; keyframeAn.repeatCount = MAXFLOAT; [self.norLayer addAnimation:keyframeAn forKey:nil]; self.replicatorLayer.instanceCount = _count; self.replicatorLayer.instanceDelay = 0.1; } - (void)reDraw { _bezierPath = nil; _count = 1; [self.norLayer removeAllAnimations]; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { [self.bezierPath stroke]; } @end
以上就是五個 Core Animation 實戰案例的完整梳理,涵蓋動態切換圖片、大轉盤、圖片折疊、進度條與粒子效果,希望對你的動畫開發有所幫助。
Android 應用目錄詳解:getFilesDir、getCacheDir 與外部儲存
內部儲存相關 getFilesDir 返回應用程式檔案目錄,透過 openFileOutput 建立的檔案會放在此處,卸載時會被刪除。getCacheDir 返回快取目錄
YingBeautyNote:類印象筆記的雲端筆記 App 實作
專案簡介YingBeautyNote 是一款類似印象筆記的 Android 筆記應用,目標是讓使用者隨時記錄生活點滴。相較於初版,V2.0 加入雲端儲存與帳號體系,使筆記
Android ListView 效能優化的幾種常見寫法
ListView 的基本原理ListView 是 Android 中常用的垂直捲動列表。它通常透過 Adapter 將資料轉換成畫面項目,而 getView 方法就是產生
仿美團點評:Android 購買欄懸浮吸頂效果實作解析
用戶體驗細節,往往決定成敗 在電商或團購 App 中,購買按鈕是否隨捲動保持可見,會直接影響操作順暢度與轉換意願。美團、大眾點評這類產品之所以順手,很大程度來自這些看似不