如何将GIF图像转换为轻量级UIImage?

时间:2014-02-17 20:10:59

标签: ios

我正在使用GIF查看器,但我的缩略图图像有问题。它们没有动画,但是当我将巨大的gif作为图像设置为imageView时,它仍然需要大量的时间和界面滞后。

以下是我的方法:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        MyCell *myCell = [collectionView
                                        dequeueReusableCellWithReuseIdentifier:@"Cell"
                                        forIndexPath:indexPath];
        UIImage *image;

        NSData *data = [NSData dataWithContentsOfURL:self.dataSource[indexPath.row]];
        image = [UIImage imageWithData:data];

        myCell.myImageView.image = image;

        return myCell;
    }

URL是本地的,因为我发现这里的瓶颈是设置巨大的GIF(每个几兆字节),因为uiimage是昂贵的并且需要时间。

如何优化此功能? 我想从我拥有的图像GIF数据创建轻量级缩略图非动画图像。我该怎么做?

编辑: 实际上我已经实现了缓存来存储它们,但这不是理想的解决方案,因为我必须偶尔清除缓存并带有内存警告。我的问题仍然有效。这是我现在的代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *myCell = [collectionView
                                    dequeueReusableCellWithReuseIdentifier:@"Cell"
                                    forIndexPath:indexPath];
    UIImage *image;

    if ([self.cache objectForKey:self.dataSource[indexPath.row]]) {

        image = [UIImage imageWithData:[self.cache objectForKey:self.dataSource[indexPath.row]]];

    } else {

        NSData *data = [NSData dataWithContentsOfURL:self.dataSource[indexPath.row]];
        image = [UIImage imageWithData:data];
    }

    myCell.myImageView.image = image;

    return myCell;
}

1 个答案:

答案 0 :(得分:3)

为了快速显示缩略图,您需要在下载图像时创建图像缩略图并将其缓存在磁盘上。对于动画GIF,您可能只想抓住第一帧,将其缩小直到只有几千字节,将其缓存到磁盘,然后显示它。这样的事情(未经测试的代码):

NSData *imageData = ...; // wherever you get your image data
UIImage *originalImage = [UIImage imageWithData:imageData];
CGSize originalSize = originalImage.size;
CGSize scaleFactor = 0.25f; // whatever scale you want
CGSize newSize = CGSizeMake(originalSize.width * scaleFactor, originalSize.height * scaleFactor);

UIGraphicsBeginImageContext(newSize);
CGRect newFrame = CGRectZero;
newFrame.size = newSize;
[originalImage drawInRect:newFrame];

UIImage *shrunkImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *pngDataToBeCached = UIImagePNGRepresentation(shrunkImage);

加载生成的PNG应该非常快。将它们保存到缓存文件夹中,以确保它们不会备份到iTunes中。还要记住,缩放和缓存图像的过程可以在后台线程上进行,以避免阻止UI。