前言
项目中有jpg图片支持progressive支持图片从模糊到清晰的加载方式,然后YYWebImage实现了该效果
主要实现方式及技术点:
一、改方式只有jpg模式支持,同时jpg模式的特点是没有透明通道,所以检测是否完整加载第一帧使用检测下载的data转换的图片里是否有透明的点
1、将data解析成图片
.....省略代码....
if (!_progressiveDecoder) {
_progressiveDecoder = [[YYImageDecoder alloc] initWithScale:[UIScreen mainScreen].scale];
}
[_progressiveDecoder updateData:_data final:NO];
.....省略代码....
YYImageFrame *frame = [_progressiveDecoder frameAtIndex:0 decodeForDisplay:YES];
UIImage *image = frame.image;
.....省略代码....
2、检测图片中是否有透明点,如果有透明点说明第一帧还没加载完成
!YYCGImageLastPixelFilled(image.CGImage)
/// Returns YES if the right-bottom pixel is filled.
static BOOL YYCGImageLastPixelFilled(CGImageRef image) {
if (!image) return NO;
size_t width = CGImageGetWidth(image);
size_t height = CGImageGetHeight(image);
if (width == 0 || height == 0) return NO;
CGContextRef ctx = CGBitmapContextCreate(NULL, 1, 1, 8, 0, YYCGColorSpaceGetDeviceRGB(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault);
if (!ctx) return NO;
CGContextDrawImage(ctx, CGRectMake( -(int)width + 1, 0, width, height), image);
uint8_t *bytes = CGBitmapContextGetData(ctx);
BOOL isAlpha = bytes && bytes[0] == 0;
CFRelease(ctx);
return !isAlpha;
}
3、加载到第一帧图后,将图片进行模糊化
[image yy_imageByBlurRadius:radius tintColor:nil tintMode:0 saturation:1 maskImage:nil];
4、在设置图片模糊化并将该图片设置到imageView上的同时,设置imageView的fade动画
if (showFade) {
CATransition *transition = [CATransition animation];
transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
}
self.image = image;
在走3+4的这个流程中,需要设置两次回调的最小时间,如果回调的最小时间小于动画的0.4s,则当次回调不做处理
根据1~4的流程,实现正常的图片渐变加载效果,然后改用加载其他类型的图片,如webp先加载一个模糊的缩略图,然后再加载大图,也能一样实现jpg的progressive的效果了
网友评论