iOS中gif图片的分解与显示

UIImageView遇到gif格式的图片能显示吗?
不能。

要让UIImageView中显示gif格式的图片应该怎么做?
只有一种办法,那就是把gif图片分解成多张静态图片,然后放在一个数组里,并使用UIImageView的属性animationImages来显示。

gif图片怎么分解成多种静态图片?
代码示例

- (NSArray *)imagesWithGif:(NSString *)gifName type:(NSString *)type
{
    // 1 获取gif数据
    NSString *gifPath = [[NSBundle mainBundle] pathForResource:gifName ofType:type];
    NSData *data = [NSData dataWithContentsOfFile:gifPath];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef) data, nil);
    // 2 获取gif有多少帧
    size_t count = CGImageSourceGetCount(source);
    NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
    for (size_t i = 0; i < count; i++) {
        CGImageRef imageref = CGImageSourceCreateImageAtIndex(source, i, NULL);
        // 3 将单帧数据转化为UIImage
        UIImage *image = [UIImage imageWithCGImage:imageref scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
        [tmpArray addObject: image];
        CGImageRelease(imageref);
    }
    CFRelease(source);
    return tmpArray;
}

使用示例

UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20, 80, 160, 160)];
[self.view addSubview:imageview];
imageview.animationImages = [self imagesWithGif:@"happy" type:@"gif"];
imageview.animationDuration = 3.0;
imageview.animationRepeatCount = 1;
[imageview startAnimating];

你可能感兴趣的:(iOS,开发编码收集)