您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

仿 BOSS 直聘下拉刷新動畫:拆解、CAShapeLayer 與 CA 動畫實作

編輯:iOS 開發基礎

轉自微信公眾號:iOS 面向編碼

BOSS 直聘的下拉刷新動畫挺有意思,我們來復刻一次。

先看最終效果:

關於實現思路

思路這東西並非唯一標準答案,每個人都有自己的偏好與套路。這裡分享我的拆解方式,拋磚引玉——深入想一想,你很可能會有更好的做法。

第一步:把動畫拆開

再複雜的動畫,都能拆成若干簡單動畫的組合。這支動畫大致可分為兩個主體,我分別錄出來看。

主體一:下拉過程中的動畫

這一段可以再切成 4 個大階段,對應 4 個點之間的 transitions:

而每個大階段又能細分為 2 個小階段(以第一、第二個點為例):

1)A → B:B 點不出現,以 A 為起點,線條從 A 一路「伸」到 B。

2)B → A:B 點出現,以 B 為終點,線條從 A 一路「縮」到 B。

合計 8 個小階段:

主體二:進入刷新狀態後的動畫

這一段則是兩個動畫的疊加:

整體旋轉:容器持續做 360 度循環旋轉。

四點位移:4 個點在一個旋轉週期內做「內 → 外 → 內 → 外」的往復移動。

選型:為什麼用 CAShapeLayer

因為只需要畫圓與線段,CAShapeLayer 是最合適的選擇。

簡介:顧名思義,CAShapeLayer 代表一個「形狀」的 Layer,是 CALayer 的子類。初始化時需要指定 Frame,但實際呈現的形狀由 path 決定,且必須指定 path,否則什麼都不會顯示。

重要屬性

1、lineWidth:線寬

2、lineCap、lineJoin:線端與轉角的樣式

3、fillColor、strokeColor:填充色與描邊色

4、path:繪圖路徑,未封閉的路徑會自動閉合

5、strokeStart、strokeEnd:繪製起訖位置,以百分比表示

動畫特點

1、與 CALayer 一樣自帶動畫能力

2、動畫僅限沿路徑變化,不支援填充區域的動畫

動畫實作

我們自訂一個 RefreshHeaderView,透過分類把它掛到 scrollView 上;下拉時驅動對應動畫。

1)四個固定位置的點

各自對應一個 Layer,路徑為圓形,填充色與路徑色一致。

CGPoint topPoint = CGPointMake(centerLine, radius);
self.TopPointLayer = [self layerWithPoint:topPoint color:topPointColor];
self.TopPointLayer.hidden = NO;
self.TopPointLayer.opacity = 0.f;
[self.layer addSublayer:self.TopPointLayer];

CGPoint leftPoint = CGPointMake(radius, centerLine);
self.LeftPointLayer = [self layerWithPoint:leftPoint color:leftPointColor];
[self.layer addSublayer:self.LeftPointLayer];

CGPoint bottomPoint = CGPointMake(centerLine, SURefreshHeaderHeight - radius);
self.BottomPointLayer = [self layerWithPoint:bottomPoint color:bottomPointColor];
[self.layer addSublayer:self.BottomPointLayer];

CGPoint rightPoint = CGPointMake(SURefreshHeaderHeight - radius, centerLine);
self.rightPointLayer = [self layerWithPoint:rightPoint color:rightPointColor];
[self.layer addSublayer:self.rightPointLayer];

- (CAShapeLayer *)layerWithPoint:(CGPoint)center color:(CGColorRef)color {
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = CGRectMake(center.x - SURefreshPointRadius, center.y - SURefreshPointRadius,
                             SURefreshPointRadius * 2, SURefreshPointRadius * 2);
    layer.fillColor = color;
    layer.path = [self pointPath];
    layer.hidden = YES;
    return layer;
}

- (CGPathRef)pointPath {
    return [UIBezierPath bezierPathWithArcCenter:CGPointMake(SURefreshPointRadius, SURefreshPointRadius)
                                          radius:SURefreshPointRadius
                                      startAngle:0
                                        endAngle:M_PI * 2
                                       clockwise:YES].CGPath;
}

2)連接四點的線條

再一個 Layer,路徑由 4 段直線拼接而成,線寬與圓點直徑一致,初始渲染起訖位置皆為 0。前面說的 8 個階段,本質上就是不斷改變這個 Layer 的 strokeStart 與 strokeEnd。

self.lineLayer = [CAShapeLayer layer];
self.lineLayer.frame = self.bounds;
self.lineLayer.lineWidth = SURefreshPointRadius * 2;
self.lineLayer.lineCap = kCALineCapRound;
self.lineLayer.lineJoin = kCALineJoinRound;
self.lineLayer.fillColor = topPointColor;
self.lineLayer.strokeColor = topPointColor;

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:topPoint];
[path addLineToPoint:leftPoint];
[path moveToPoint:leftPoint];
[path addLineToPoint:bottomPoint];
[path moveToPoint:bottomPoint];
[path addLineToPoint:rightPoint];
[path moveToPoint:rightPoint];
[path addLineToPoint:topPoint];

self.lineLayer.path = path.CGPath;
self.lineLayer.strokeStart = 0.f;
self.lineLayer.strokeEnd = 0.f;
[self.layer insertSublayer:self.lineLayer above:self.TopPointLayer];

3)用下拉距離控制動畫進度

核心是依下拉長度算出線條的起訖位置,並在恰當時機顯示或隱藏對應的點。

- (void)setLineLayerStrokeWithProgress:(CGFloat)progress {
    float startProgress = 0.f;
    float endProgress = 0.f;

    // 未下拉:隱藏動畫
    if (progress < 0) {
        self.TopPointLayer.opacity = 0.f;
        [self adjustPointStateWithIndex:0];
    }
    // 下拉前奏:頂部圓點漸顯
    else if (progress >= 0 && progress < (SURefreshPullLen - 40)) {
        self.TopPointLayer.opacity = progress / 20;
        [self adjustPointStateWithIndex:0];
    }
    // 正式動畫:劃分為 4 個大階段
    else if (progress >= (SURefreshPullLen - 40) && progress < SURefreshPullLen) {
        self.TopPointLayer.opacity = 1.0;

        // 大階段 0 ~ 3
        NSInteger stage = (progress - (SURefreshPullLen - 40)) / 10;

        // 大階段內的前半段進度
        CGFloat subProgress = (progress - (SURefreshPullLen - 40)) - (stage * 10);

        if (subProgress >= 0 && subProgress < 5) {
            [self adjustPointStateWithIndex:stage * 2];
            startProgress = stage / 4.0;
            endProgress = stage / 4.0 + subProgress / 40.0;
        }
        else if (subProgress >= 5 && subProgress < 10) {
            [self adjustPointStateWithIndex:stage * 2 + 1];
            startProgress = stage / 4.0 + (subProgress - 5) / 40.0 * 2;
            if (startProgress < (stage + 1) / 4.0 - 0.1) {
                startProgress = (stage + 1) / 4.0 - 0.1;
            }
            endProgress = (stage + 1) / 4.0;
        }
    }
    // 下拉足夠長:四點全數顯示
    else {
        self.TopPointLayer.opacity = 1.0;
        [self adjustPointStateWithIndex:NSIntegerMax];
        startProgress = 1.0;
        endProgress = 1.0;
    }

    self.lineLayer.strokeStart = startProgress;
    self.lineLayer.strokeEnd = endProgress;
}

- (void)adjustPointStateWithIndex:(NSInteger)index {
    // index 為小階段:0 ~ 7
    self.LeftPointLayer.hidden   = index > 1 ? NO : YES;
    self.BottomPointLayer.hidden = index > 3 ? NO : YES;
    self.rightPointLayer.hidden  = index > 5 ? NO : YES;

    self.lineLayer.strokeColor = index > 5 ? rightPointColor
                             : index > 3 ? bottomPointColor
                             : index > 1 ? leftPointColor
                             : topPointColor;
}

4)達到條件時進入刷新狀態

進入刷新的條件有三個:下拉長度已超過設定閾值、手指已離開螢幕(scrollView 不再處於拖動狀態)、目前沒有正在播放 Loading 動畫。進入時同時觸發真正的刷新業務(例如發請求)。

// 非刷新中:播放漸變收尾動畫
if (!self.animating) {
    if (progress >= SURefreshPullLen) {
        self.y = -(SURefreshPullLen - (SURefreshPullLen - SURefreshHeaderHeight) / 2);
    } else {
        ...
    }
}

if (progress >= SURefreshPullLen && !self.animating && !self.scrollView.dragging) {
    [self startAni];
    if (self.handle) {
        self.handle();
    }
}

Loading 動畫以 CA 動畫完成,共三個部分。

scrollView 下沉

[UIView animateWithDuration:0.5 animations:^{
    UIEdgeInsets inset = self.scrollView.contentInset;
    inset.top = SURefreshPullLen;
    self.scrollView.contentInset = inset;
}];

四點往復位移

[self addTranslationAniToLayer:self.TopPointLayer    xValue:0                    yValue:SURefreshTranslatLen];
[self addTranslationAniToLayer:self.LeftPointLayer   xValue:SURefreshTranslatLen  yValue:0];
[self addTranslationAniToLayer:self.BottomPointLayer xValue:0                    yValue:-SURefreshTranslatLen];
[self addTranslationAniToLayer:self.rightPointLayer  xValue:-SURefreshTranslatLen yValue:0];

- (void)addTranslationAniToLayer:(CALayer *)layer xValue:(CGFloat)x yValue:(CGFloat)y {
    CAKeyframeAnimation *translationKeyframeAni = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    translationKeyframeAni.duration = 1.0;
    translationKeyframeAni.repeatCount = HUGE;
    translationKeyframeAni.removedOnCompletion = NO;
    translationKeyframeAni.fillMode = kCAFillModeForwards;
    translationKeyframeAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    NSValue *fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, 0, 0.f)];
    NSValue *toValue   = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(x, y, 0.f)];

    translationKeyframeAni.values = @[fromValue, toValue, fromValue, toValue, fromValue];
    [layer addAnimation:translationKeyframeAni forKey:@"translationKeyframeAni"];
}

整體旋轉

[self addRotationAniToLayer:self.layer];

- (void)addRotationAniToLayer:(CALayer *)layer {
    CABasicAnimation *rotationAni = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAni.fromValue = @(0);
    rotationAni.toValue = @(M_PI * 2);
    rotationAni.duration = 1.0;
    rotationAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    rotationAni.repeatCount = HUGE;
    rotationAni.fillMode = kCAFillModeForwards;
    rotationAni.removedOnCompletion = NO;
    [layer addAnimation:rotationAni forKey:@"rotationAni"];
}

5)回到初始狀態

當下拉距離不到臨界值,或 Loading 結束時,移除所有動畫並復位。

- (void)removeAni {
    [UIView animateWithDuration:0.5 animations:^{
        UIEdgeInsets inset = self.scrollView.contentInset;
        inset.top = 0.f;
        self.scrollView.contentInset = inset;
    } completion:^(BOOL finished) {
        [self.TopPointLayer    removeAllAnimations];
        [self.LeftPointLayer   removeAllAnimations];
        [self.BottomPointLayer removeAllAnimations];
        [self.rightPointLayer  removeAllAnimations];
        [self.layer removeAllAnimations];
        [self adjustPointStateWithIndex:0];
        self.animating = NO;
    }];
}

接入方式

建立一個 UIScrollView 的分類,對外提供一個掛上 RefreshHeader 的方法:

- (void)addRefreshHeaderWithHandle:(void (^)())handle {
    SURefreshHeader *header = [[SURefreshHeader alloc] init];
    header.handle = handle;
    self.header = header;
    [self insertSubview:header atIndex:0];
}

分類無法直接宣告 Property,所以改用關聯物件把 header 綁到 scrollView 上:

objc_setAssociatedObject(self, @selector(header), header, OBJC_ASSOCIATION_ASSIGN);

想一想:這裡為什麼用 ASSIGN 這個關聯策略?

另外,scrollView 銷毀時 header 也會一起消失,但 header 是 scrollView 的觀察者,不移除就會崩潰。因此在 scrollView 的 dealloc 中必須完成移除,這裡同樣用方法交換處理:

+ (void)load {
    Method originalMethod = class_getInstanceMethod([self class], NSSelectorFromString(@"dealloc"));
    Method swizzleMethod  = class_getInstanceMethod([self class], NSSelectorFromString(@"su_dealloc"));
    method_exchangeImplementations(originalMethod, swizzleMethod);
}

- (void)su_dealloc {
    self.header = nil;
    [self su_dealloc];
}

再想一個問題:在這份程式碼中,ScrollView、RefreshHeader、RefreshBlock 三者的引用關係究竟如何?試著畫一張示意圖,對理解記憶體管理很有幫助。

走到這一步,我們自己寫的下拉刷新元件就能像 MJRefresh 一樣方便地用在專案裡了。

[self.tableView addRefreshHeaderWithHandle:^{
    // 請求網路資料
}];

// 請求完成後
[tableView.header endRefreshing];

Demo

本文的 demo 已放在我的 GitHub 上:https://github.com/DaMingShen/SURefresh

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved