思路一 給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圖的
注意:關(guān)閉webview的交互妙真。瑰妄。蕉鸳。