簡體   English   中英

如何將GIF圖像轉換為輕量級的UIImage?

[英]How to turn GIF image into lightweight UIImage?

我正在使用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;
}

為了快速顯示縮略圖,您需要在下載圖像時為其創建縮略圖並將其緩存在磁盤上。 對於動畫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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM