您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 碎片(像素化消散)動畫詳解

編輯:iOS 相關教學

效果圖

遮罩視圖

這個動畫的關鍵是 UIView 的 maskView 屬性(iOS 8 之後提供)。什麼是遮罩?簡單說,一個視圖除了可以用 alpha 調整透明度,還可以指定另一個視圖當遮罩,由遮罩決定「哪裡看得到、哪裡看不到」。兩者的差別只在於:alpha 是 0~1 的數值,而遮罩視圖的 backgroundColor、alpha、transform 等屬性都會影響最終的顯示效果。

先看一段程式碼:

UIView *viewContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
viewContainer.backgroundColor = [UIColor blueColor];

UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 160, 160)];
contentView.backgroundColor = [UIColor redColor];
[viewContainer addSubview:contentView];

UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 35, 80)];
maskView.backgroundColor = [UIColor yellowColor];
contentView.maskView = maskView;

遮罩視圖決定了視圖的顯示內容

接著分別改 maskView 與 contentView 的透明度,會發現效果完全一樣:

修改透明度的結果

結論:遮罩對視圖的影響,直接反映在「透明度」與「可見尺寸」這兩件事上。

顏色

當顏色不含透明成分時,視圖不會有透明效果。但若把遮罩顏色設成半透明:

maskView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5]; // 任意顏色

視覺上等於直接設 alpha = 0.5。也就是說,遮罩只取用 alpha 通道,與 RGB 值無關。

maskView 的子視圖

maskView.backgroundColor = [UIColor clearColor];

UIView *sub1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 34)];
sub1.backgroundColor = [UIColor blackColor];

UIView *sub2 = [[UIView alloc] initWithFrame:CGRectMake(15, 18, 33, 40)];
sub2.backgroundColor = [UIColor blackColor];

[maskView addSubview:sub1];
[maskView addSubview:sub2];

為了排除遮罩自身的干擾,這裡把 maskView 背景設為透明。

子視圖也會參與遮罩運算

可見即使遮罩本身透明,子視圖仍能構成部分遮罩。因此只要改變子視圖的 alpha,遮罩效果也會跟著改變——這正是碎片動畫的基礎。

動畫實作

回到效果圖:圖片被切成許多小方塊逐塊消失,垂直切成 2 份、水平約 15 份。所以我們在 maskView 上均勻擺放 2 × 15 個子視圖,並給每個加上可識別的 tag:

UIView *maskView = [[UIView alloc] initWithFrame:contentView.bounds];
const NSInteger horizontalCount = 15;
const NSInteger verticalCount = 2;
const CGFloat fadeWidth = CGRectGetWidth(maskView.frame) / horizontalCount;
const CGFloat fadeHeight = CGRectGetHeight(maskView.frame) / verticalCount;

for (NSInteger line = 0; line < horizontalCount; line++) {
    for (NSInteger row = 0; row < verticalCount; row++) {
        CGRect frame = CGRectMake(line * fadeWidth, row * fadeHeight,
                                  fadeWidth, fadeHeight);
        UIView *fadeView = [[UIView alloc] initWithFrame:frame];
        fadeView.tag = [self viewTag:line * verticalCount + row];
        fadeView.backgroundColor = [UIColor whiteColor];
        [maskView addSubview:fadeView];
    }
}
contentView.maskView = maskView;

接著遍歷這些子視圖,用 delay 讓它們依序淡出:

for (NSInteger line = 0; line < horizontalCount; line++) {
    for (NSInteger row = 0; row < verticalCount; row++) {
        NSInteger idx = line * verticalCount + row;
        UIView *fadeView = [contentView.maskView viewWithTag:[self viewTag:idx]];
        [UIView animateWithDuration:fadeDuration
                              delay:interval * idx
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{ fadeView.alpha = 0; }
                         completion:nil];
    }
}

封裝成 Category

寫動畫時都該想著「怎麼讓它以後能重複使用」。上面這段完全可以封裝成 UIView 的分類,降低對既有程式碼的侵入:

#define LXDMAXDURATION 1.2
#define LXDMINDURATION .2
#define LXDMULTIPLED .25

@interface UIView (LXDFadeAnimation)
/*! @brief 視圖是否已隱藏 */
@property (nonatomic, assign, readonly) BOOL isFade;
/*! @brief 是否處在動畫中 */
@property (nonatomic, assign, readonly) BOOL isFading;
/*! @brief 垂直方塊個數,預設 3 */
@property (nonatomic, assign) NSInteger verticalCount;
/*! @brief 水平方塊個數,預設 18 */
@property (nonatomic, assign) NSInteger horizontalCount;
/*! @brief 方塊動畫間隔,預設 0.7 */
@property (nonatomic, assign) NSTimeInterval intervalDuration;
/*! @brief 單一方塊動畫時間,預設 0.175 */
@property (nonatomic, assign) NSTimeInterval fadeAnimationDuration;

- (void)configurateWithVerticalCount:(NSInteger)verticalCount
                     horizontalCount:(NSInteger)horizontalCount
                            interval:(NSTimeInterval)interval
                            duration:(NSTimeInterval)duration;
- (void)animateFadeWithComplete:(void(^)(void))complete;
- (void)reverseWithComplete:(void(^)(void))complete;
- (void)reverseWithoutAnimate;
@end

在 category 中宣告的屬性,編譯器不會自動合成 getter/setter,也不能直接用「底線 + 名稱」存取 Ivar。因此需要引入 objc/runtime.h,用關聯物件(associated object)動態掛上屬性:

#import <objc/runtime.h>

static const void *kIsFadeKey = &kIsFadeKey;
// 其他 key 同理

- (BOOL)isFade {
    return [objc_getAssociatedObject(self, kIsFadeKey) boolValue];
}

- (void)setIsFade:(BOOL)isFade {
    objc_setAssociatedObject(self, kIsFadeKey, @(isFade),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
// 其他 getter / setter 依此類推

有了消散動畫,自然也該有還原動畫,順序剛好相反:

NSInteger fadeCount = self.verticalCount * self.horizontalCount;
for (NSInteger idx = fadeCount - 1; idx >= 0; idx--) {
    UIView *subview = [self.maskView viewWithTag:[self subViewTag:idx]];
    [UIView animateWithDuration:self.fadeAnimationDuration
                          delay:self.intervalDuration * (fadeCount - 1 - idx)
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{ subview.alpha = 1; }
                     completion:nil];
}

接著有個問題要處理:使用者可能連續點擊。我們必須在動畫進行中忽略新的觸發,並且在「最後一個方塊」的動畫完成時,才知道整體動畫結束。用一個計數器即可:

__block NSInteger timeCount = 0;
// ...
[UIView animateWithDuration:self.fadeAnimationDuration
                      delay:self.intervalDuration * (fadeCount - 1 - idx)
                    options:UIViewAnimationOptionCurveLinear
                 animations:^{ subview.alpha = 1; }
                 completion:^(BOOL finished) {
    if (++timeCount == fadeCount) {
        self.isFade = NO;
        self.isFading = NO;
        if (complete) {
            complete();
        }
    }
}];
// ...

有了完成時機,就能對外提供一個 block 讓呼叫者在動畫結束後接續處理。

輪播碎片動畫

掌握碎片動畫之後,可以做一個更有趣的廣告輪播頁,同樣以 category 實作:

廣告輪播頁

需要哪些步驟?

1. 在目前圖片下方插入一個 UIImageView 預先放好「下一張」,並盡量重複使用同一個實例。

2. 加上 UIPageControl 標示目前頁碼。

對外提供一個傳入圖片陣列的接口:

// 取得關聯綁定的臨時 UIImageView
- (UIImageView *)associateTempBannerWithImage:(UIImage *)image {
    UIImageView *tempBanner = objc_getAssociatedObject(self, kTempImageKey);
    if (!tempBanner) {
        tempBanner = [[UIImageView alloc] initWithFrame:self.frame];
        objc_setAssociatedObject(self, kTempImageKey, tempBanner,
                                 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self.superview insertSubview:tempBanner belowSubview:self];
    }
    tempBanner.image = image;
    return tempBanner;
}

pageControl 一開始加在執行動畫的 imageView 上,但動畫進行到一半時它也會跟著被遮掉。因此要依 imageView 實際座標另外算一個位置:

- (void)associatePageControlWithCurrentIdx:(NSInteger)idx {
    UIPageControl *pageControl = objc_getAssociatedObject(self, kPageControlKey);
    if (!pageControl) {
        pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(
            self.frame.origin.x,
            CGRectGetHeight(self.frame) - 37 + self.frame.origin.y,
            CGRectGetWidth(self.frame), 37)];
        [self.superview addSubview:pageControl];
        pageControl.numberOfPages = self.bannerImages.count;
        objc_setAssociatedObject(self, kPageControlKey, pageControl,
                                 OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    pageControl.currentPage = idx;
}

由於每輪動畫結束後都要再跑一次同樣的流程,我們把「切換」這段邏輯宣告成一個 block 變數,並用 __block 修飾索引,讓回呼中能更新它:

- (void)fadeBanner {
    NSParameterAssert(self.superview);

    UIImageView *tempBanner = [self associateTempBannerWithImage:
                               [UIImage imageNamed:self.bannerImages[1]]];
    self.stop = NO;

    __block NSInteger idx = 0;
    __weak typeof(self) weakSelf = self;
    [self associatePageControlWithCurrentIdx:idx];

    void (^complete)(void) = ^{
        NSInteger updateIndex = [weakSelf updateImageWithCurrentIndex:++idx
                                                          tempBanner:tempBanner];
        idx = updateIndex;
        [weakSelf associatePageControlWithCurrentIdx:idx];
    };

    // 把 block 動態保存起來,並啟動動畫
    objc_setAssociatedObject(self, kCompleteBlockKey, complete,
                             OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self animateFadeWithComplete:^{
        if (!self.stop) {
            complete();
        }
    }];
}

// 更新圖片並回傳下一次要顯示的索引
- (NSInteger)updateImageWithCurrentIndex:(NSInteger)idx
                              tempBanner:(UIImageView *)tempBanner {
    if (idx >= self.bannerImages.count) {
        idx = 0;
    }
    self.image = [UIImage imageNamed:self.bannerImages[idx]];
    [self reverseWithoutAnimate];

    NSInteger nextIdx = idx + 1;
    if (nextIdx >= self.bannerImages.count) {
        nextIdx = 0;
    }
    tempBanner.image = [UIImage imageNamed:self.bannerImages[nextIdx]];

    [self animateFadeWithComplete:^{
        if (!self.stop) {
            void (^complete)(void) = objc_getAssociatedObject(self, kCompleteBlockKey);
            complete();
        }
    }];
    return idx;
}

這裡最容易踩的雷是 block 的生命週期:這個完成回呼必須用 objc_Associate 動態保存。即使你把更新圖片的程式碼直接寫進 complete 裡,也一樣要保存起來,否則 block 跑到第三次就會被釋放而崩潰。另外記得用 __weak 持有 self,避免循環引用。

每次切換完成後,別忘了把所有遮罩子視圖還原,並更新顯示:

- (void)reverseWithoutAnimate {
    if (self.isFading) {
        NSLog(@"It's animating!");
        return;
    }
    for (UIView *subview in self.maskView.subviews) {
        subview.alpha = 1;
    }
}

總結

整個碎片動畫的核心其實只有兩件事:用 maskView 決定可見範圍,再對遮罩的子視圖批次跑 alpha 動畫。剩下的都是工程細節——狀態標記、完成時機、block 記憶體管理。把這些處理好,這個效果就能安全地用在正式專案裡。

以上就是 iOS 實作碎片動畫的完整解析,希望對大家開發動畫時有幫助。

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