從零開始打造一個iOS圖片載入框架(二)

醬了裡個醬發表於2019-03-28

一、前言

上一章節主要講解了圖片的簡單載入、記憶體/磁碟快取等內容,但目前該框架還不支援GIF圖片的載入。而GIF圖片在我們日常開發中是非常常見的。因此,本章節將著手實現對GIF圖片的載入。

二、載入GIF圖片

1. 載入本地GIF圖片

UIImageView本身是支援對GIF圖片的載入的,將GIF圖片加入到animationImages屬性中,並通過startAnimatingstopAnimating來啟動/停止動畫。

UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:    
                               [UIImage imageNamed:@"image1.gif"],
                               [UIImage imageNamed:@"image2.gif"],
                               [UIImage imageNamed:@"image3.gif"],
                               [UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];
複製程式碼

2.載入網路GIF圖片

與本地載入的不同之處在於我們通過網路獲取到的是NSData型別,如果只是簡單地通過initImageWithData:方法轉化為image,那麼往往只能獲取到GIF中的第一張圖片。我們知道GIF圖片其實就是由於多張圖片組合而成。因此,我們這裡最重要是如何從NSData中解析轉化為images

  • JImageCoder:我們定義一個類轉化用於影象的解析
@interface JImageCoder : NSObject
+ (instancetype)shareCoder;
- (UIImage *)decodeImageWithData:(NSData *)data;
@end
複製程式碼

我們知道通過網路請求下載之後返回的是NSData資料

 NSURLSessionDataTask *dataTask = [self.session dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //do something: data->image
 }];
複製程式碼

對於PNG和JPEG格式我們可以直接使用initImageWithData方法來轉化為image,但對於GIF圖片,我們則需要特殊處理。那麼處理之前,我們就需要根據NSData來判斷圖片對應的格式。

  • 根據NSData資料判斷圖片格式:這裡參考了SDWebImage的實現,根據資料的第一個位元組來判斷。
- (JImageFormat)imageFormatWithData:(NSData *)data {
    if (!data) {
        return JImageFormatUndefined;
    }
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return JImageFormatJPEG;
        case 0x89:
            return JImageFormatPNG;
        case 0x47:
            return JImageFormatGIF;
        default:
            return JImageFormatUndefined;
    }
}
複製程式碼

獲取到圖片的格式之後,我們就可以根據不同的格式來分別進行處理

- (UIImage *)decodeImageWithData:(NSData *)data {
    JImageFormat format = [self imageFormatWithData:data];
    switch (format) {
        case JImageFormatJPEG:
        case JImageFormatPNG:{
            UIImage *image = [[UIImage alloc] initWithData:data];
            image.imageFormat = format;
            return image;
        }
        case JImageFormatGIF:
            return [self decodeGIFWithData:data];
        default:
            return nil;
    }
}
複製程式碼

針對GIF圖片中的每張圖片的獲取,我們可以使用ImageIO中的相關方法來提取。要注意的是對於一些物件,使用完之後要及時釋放,否則會造成記憶體洩漏。

- (UIImage *)decodeGIFWithData:(NSData *)data {
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!source) {
        return nil;
    }
    size_t count = CGImageSourceGetCount(source);
    UIImage *animatedImage;
    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
        animatedImage.imageFormat = JImageFormatGIF;
    } else {
        NSMutableArray<UIImage *> *imageArray = [NSMutableArray array];
        for (size_t i = 0; i < count; i ++) {
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
            if (!imageRef) {
                continue;
            }
            UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
            [imageArray addObject:image];
            CGImageRelease(imageRef);
        }
        animatedImage = [[UIImage alloc] init];
        animatedImage.imageFormat = JImageFormatGIF;
        animatedImage.images = [imageArray copy];
    }
    CFRelease(source);
    return animatedImage;
}
複製程式碼

為了使得UIImage物件可以儲存圖片的格式和GIF中的images,這裡實現了一個UIImage的分類

typedef NS_ENUM(NSInteger, JImageFormat) {
    JImageFormatUndefined = -1,
    JImageFormatJPEG = 0,
    JImageFormatPNG = 1,
    JImageFormatGIF = 2
};
@interface UIImage (JImageFormat)
@property (nonatomic, assign) JImageFormat imageFormat;
@property (nonatomic, copy) NSArray *images;
@end

@implementation UIImage (JImageFormat)
- (void)setImages:(NSArray *)images {
    objc_setAssociatedObject(self, @selector(images), images, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSArray *)images {
    NSArray *images = objc_getAssociatedObject(self, @selector(images));
    if ([images isKindOfClass:[NSArray class]]) {
        return images;
    }
    return nil;
}
- (void)setImageFormat:(JImageFormat)imageFormat {
    objc_setAssociatedObject(self, @selector(imageFormat), @(imageFormat), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (JImageFormat)imageFormat {
    JImageFormat imageFormat = JImageFormatUndefined;
    NSNumber *value = objc_getAssociatedObject(self, @selector(imageFormat));
    if ([value isKindOfClass:[NSNumber class]]) {
        imageFormat = value.integerValue;
        return imageFormat;
    }
    return imageFormat;
}
@end
複製程式碼

使用JImageCoderNSData型別的資料解析為images之後,便可以像本地載入GIF一樣使用了。

static NSString *gifUrl = @"https://user-gold-cdn.xitu.io/2019/3/27/169bce612ee4dc21";
- (void)downloadImage {
    __weak typeof(self) weakSelf = self;
    [[JImageDownloader shareInstance] fetchImageWithURL:gifUrl completion:^(UIImage * _Nullable image, NSError * _Nullable error) {
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (strongSelf && image) {
            if (image.imageFormat == JImageFormatGIF) {
                strongSelf.imageView.animationImages = image.images;
                [strongSelf.imageView startAnimating];
            } else {
                strongSelf.imageView.image = image;
            }
        }
    }];
}
複製程式碼

3.實現效果

從零開始打造一個iOS圖片載入框架(二)

YYAnimatedImageFLAnimatedImage分別進行了對比,會發現自定義框架載入的GIF播放會更快些。我們回到UIImageView的GIF本地載入中,會發現遺漏了兩個重要的屬性:

@property (nonatomic) NSTimeInterval animationDuration;         // for one cycle of images. default is number of images * 1/30th of a second (i.e. 30 fps)
@property (nonatomic) NSInteger      animationRepeatCount;      // 0 means infinite (default is 0)
複製程式碼

animatedDuration定義了動畫的週期,由於我們沒有給它設定GIF的週期,所以這裡使用的預設週期。接下來我們將回到GIF圖片的解析過程中,增加這兩個相關屬性。

4.GIF的animationDurationanimationRepeatCount屬性

  • animationRepeatCount:動畫執行的次數
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
....
NSInteger loopCount = 0;
CFDictionaryRef properties = CGImageSourceCopyProperties(source, NULL);
if (properties) {
    CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
    if (gif) {
        CFTypeRef loop = CFDictionaryGetValue(gif, kCGImagePropertyGIFLoopCount);
        if (loop) {
            CFNumberGetValue(loop, kCFNumberNSIntegerType, &loopCount);
        }
    }
    CFRelease(properties); //注意使用完需要釋放
}
複製程式碼
  • animationDuration:動畫執行週期

我們分別獲取到GIF中每張圖片對應的delayTime(顯示時間),最後求它們的和,便可以作為GIF動畫的一個完整週期。而圖片的delayTime可以通過ImageSource中的kCGImagePropertyGIFUnclampedDelayTimekCGImagePropertyGIFDelayTime屬性獲取。

NSTimeInterval duration = 0;
for (size_t i = 0; i < count; i ++) {
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
    if (!imageRef) {
        continue;
    }
    ....
    float delayTime = kJAnimatedImageDefaultDelayTimeInterval;
    CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
    if (properties) {
        CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
        if (gif) {
            CFTypeRef value = CFDictionaryGetValue(gif, kCGImagePropertyGIFUnclampedDelayTime);
            if (!value) {
                value = CFDictionaryGetValue(gif, kCGImagePropertyGIFDelayTime);
            }
            if (value) {
                CFNumberGetValue(value, kCFNumberFloatType, &delayTime);
            }
        }
        CFRelease(properties);
    }
    duration += delayTime;
}
複製程式碼

獲取之後加入到UIImage屬性中:

animatedImage = [[UIImage alloc] init];
animatedImage.imageFormat = JImageFormatGIF;
animatedImage.images = [imageArray copy];
animatedImage.loopCount = loopCount;
animatedImage.totalTimes = duration;

- (void)downloadImage {
    __weak typeof(self) weakSelf = self;
    [[JImageDownloader shareInstance] fetchImageWithURL:gifUrl completion:^(UIImage * _Nullable image, NSError * _Nullable error) {
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (strongSelf && image) {
            if (image.imageFormat == JImageFormatGIF) {
                strongSelf.imageView.animationImages = image.images;
                strongSelf.imageView.animationDuration = image.totalTimes;
                strongSelf.imageView.animationRepeatCount = image.loopCount;
                [strongSelf.imageView startAnimating];
            } else {
                strongSelf.imageView.image = image;
            }
        }
    }];
}
複製程式碼

實現效果如下:

設定週期前 設定週期後

發現通過設定動畫週期和次數之後,動畫載入的更快了!!!為了解決這個問題,重新閱讀了YYAnimatedImageFLAnimatedImage的原始碼,發現它們在獲取GIF圖片的delayTime時,都會有一個小小的細節。

FLAnimatedImage.m
const NSTimeInterval kFLAnimatedImageDelayTimeIntervalMinimum = 0.02;
const NSTimeInterval kDelayTimeIntervalDefault = 0.1;
// Support frame delays as low as `kFLAnimatedImageDelayTimeIntervalMinimum`, with anything below being rounded up to `kDelayTimeIntervalDefault` for legacy compatibility.
// To support the minimum even when rounding errors occur, use an epsilon when comparing. We downcast to float because that's what we get for delayTime from ImageIO.
if ([delayTime floatValue] < ((float)kFLAnimatedImageDelayTimeIntervalMinimum - FLT_EPSILON)) {
    FLLog(FLLogLevelInfo, @"Rounding frame %zu's `delayTime` from %f up to default %f (minimum supported: %f).", i, [delayTime floatValue], kDelayTimeIntervalDefault, kFLAnimatedImageDelayTimeIntervalMinimum);
    delayTime = @(kDelayTimeIntervalDefault);
}

UIImage+YYWebImage.m
static NSTimeInterval _yy_CGImageSourceGetGIFFrameDelayAtIndex(CGImageSourceRef source, size_t index) {
    NSTimeInterval delay = 0;
    CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(source, index, NULL);
    if (dic) {
        CFDictionaryRef dicGIF = CFDictionaryGetValue(dic, kCGImagePropertyGIFDictionary);
        if (dicGIF) {
            NSNumber *num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFUnclampedDelayTime);
            if (num.doubleValue <= __FLT_EPSILON__) {
                num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFDelayTime);
            }
            delay = num.doubleValue;
        }
        CFRelease(dic);
    }
    // http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser-compatibility
    if (delay < 0.02) delay = 0.1;
    return delay;
}
複製程式碼

如上所示,YYAnimatedImageFLAnimatedImage對於delayTime小於0.02的情況下,都會設定為預設值0.1。這麼處理的主要目的是為了更好相容更低階的裝置,具體可以檢視這裡

static const NSTimeInterval kJAnimatedImageDelayTimeIntervalMinimum = 0.02;
static const NSTimeInterval kJAnimatedImageDefaultDelayTimeInterval = 0.1;
float delayTime = kJAnimatedImageDefaultDelayTimeInterval;
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
if (properties) {
    CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
    if (gif) {
        CFTypeRef value = CFDictionaryGetValue(gif, kCGImagePropertyGIFUnclampedDelayTime);
        if (!value) {
            value = CFDictionaryGetValue(gif, kCGImagePropertyGIFDelayTime);
        }
        if (value) {
            CFNumberGetValue(value, kCFNumberFloatType, &delayTime);
            if (delayTime < ((float)kJAnimatedImageDelayTimeIntervalMinimum - FLT_EPSILON)) {
                delayTime = kJAnimatedImageDefaultDelayTimeInterval;
            }
        }
    }
    CFRelease(properties);
}
duration += delayTime;
複製程式碼

為了讓動畫效果更接近YYAnimatedImageFLAnimatedImage,我們同樣在獲取delayTime時增加條件判斷。具體效果如下:

動畫三

三、總結

本小節主要實現了圖片框架對GIF圖片的載入功能。重點主要集中在通過ImageIO中的相關方法來獲取到GIF中的每張圖片,以及圖片對應的週期和執行次數等。在最後結尾處也提及到了在獲取圖片delayTime時的一個小細節。通過這個細節也可以體現出自己動手打造框架的好處,因為如果只是簡單地去閱讀相關原始碼,往往很容易忽略很多細節。

參考資料

相關文章