今天查阅直播优化相关文章的时候看到一篇文章之后对帧动画有了新的认识,在这记录一下,首先借用一下原版主的Git图看看效果
效果1:使用异步加载(定时器更换读取到的图片位图)
- 我这里就放核心的代码,这里就是异步解压缩,在定时器回调中为
layer.contents
赋值
UIImage *frame = self.frameImages[bImgIndex];
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
CGImageRef copyImageRef = [frame cc_decodedCGImageRefCopy];//重点
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.layer.contents = (__bridge_transfer id)copyImageRef;
});
});
- 解压缩工具类
UIImage+keyFrameDecoder.h
#import <UIKit/UIKit.h>
@interface UIImage (keyFrameDecoder)
- (nullable CGImageRef)cc_decodedCGImageRefCopy;
@end
UIImage+keyFrameDecoder.m
#import "UIImage+keyFrameDecoder.h"
@implementation UIImage (keyFrameDecoder)
- (nullable CGImageRef)cc_decodedCGImageRefCopy {
CGImageRef imgRef = self.CGImage;
if (!imgRef) {
return NULL;
}
size_t imgWidth = CGImageGetWidth(imgRef);
size_t imgHeight = CGImageGetHeight(imgRef);
if (0 == imgWidth || 0 == imgHeight) {
return NULL;
}
const size_t cBPC = 8;
const size_t cBytesPR = 0;
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imgRef);
BOOL hasAlpha = (kCGImageAlphaPremultipliedFirst == alphaInfo
|| kCGImageAlphaPremultipliedLast == alphaInfo
|| kCGImageAlphaFirst == alphaInfo
|| kCGImageAlphaLast == alphaInfo);
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
CGContextRef context = CGBitmapContextCreate(NULL,
imgWidth,
imgHeight,
cBPC,
cBytesPR,
CGColorSpaceCreateDeviceRGB(),
bitmapInfo);
if (context) {
CGContextDrawImage(context,
CGRectMake(0, 0, imgWidth, imgHeight),
imgRef);
imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imgRef;
}
return NULL;
}
@end
效果2:使用系统再带的animationImages
属性实现的,就是CAAnimation及其派生类
for (int i = 1; i<66; i++) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"img%d",i] ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
if (image) {
[imageArray addObject:image];
}
}
self.imageView.animationImages = imageArray;
self.imageView.animationDuration = 8;
self.imageView.animationRepeatCount = 1;
[self.imageView startAnimating];
我这里简单总结一下,感兴趣的小伙伴们可以移步原文