美文网首页
UIImageView支持动图(gif)

UIImageView支持动图(gif)

作者: xxzsxxzs | 来源:发表于2016-10-07 20:19 被阅读48次

    思路一 给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的交互。。。

    相关文章

      网友评论

          本文标题:UIImageView支持动图(gif)

          本文链接:https://www.haomeiwen.com/subject/bynyyttx.html