UIImageView支持动图(gif)
思路一 给UIImageView 扩展一个Category
基于Image I/O CGImageSourceRef、CGImageDestinationRef
- (void)showGifImageWithData:(NSData *)data {
//获取动画时长
NSTimeInterval duration = [self durationForGifData:data];
//image sources
CGImageSourceRef source = CGImageSourceCreateWithData(toCF data, NULL);
//动画
[self animatedGIFImageSource:source andDuration:duration];
CFRelease(source);
}
- (NSTimeInterval)durationForGifData:(NSData *)data {
char graphicControlExtensionStartBytes[] = {0x21,0xF9,0x04};
double duration=0;
NSRange dataSearchLeftRange = NSMakeRange(0, data.length);
while(YES){
NSRange frameDescriptorRange = [data rangeOfData:[NSData dataWithBytes:graphicControlExtensionStartBytes
length:3]
options:NSDataSearchBackwards
range:dataSearchLeftRange];
if(frameDescriptorRange.location!=NSNotFound){
NSData *durationData = [data subdataWithRange:NSMakeRange(frameDescriptorRange.location+4, 2)];
unsigned char buffer[2];
[durationData getBytes:buffer];
double delay = (buffer[0] | buffer[1] << 8);
duration += delay;
dataSearchLeftRange = NSMakeRange(0, frameDescriptorRange.location);
}else{
break;
}
}
return duration/100;
}
- (void)animatedGIFImageSource:(CGImageSourceRef) source
andDuration:(NSTimeInterval) duration {
if (!source) return;
size_t count = CGImageSourceGetCount(source);
NSMutableArray *images = [NSMutableArray arrayWithCapacity:count];
for (size_t i = 0; i < count; ++i) {
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, i, NULL);
if (!cgImage)
return;
[images addObject:[UIImage imageWithCGImage:cgImage]];
CGImageRelease(cgImage);
}
[self setAnimationImages:images];
[self setAnimationDuration:duration];
[self startAnimating];
}
思路二:已知webview 是可以加载gif图的
注意:关闭webview的交互。。。