关于iphone:避免图片解压阻塞主线程

Avoid image decompression blocking the main thread

我有一些代码可以使用 UIImageView 显示动画 GIF 图像,这里:https://github.com/amleszk/GifBlocking

它适用于 99% 的情况,尽管某些类型的 GIF 图像存在问题,可以在此处找到示例:http://i.imgur.com/mbImw.gif

这个 gif 可以接收 101 张图片,然后在显示包含动画图片的 UIImageView 时阻塞主线程。如果它有压缩,解压缩 gif 很好,但是我将如何阻止它阻塞主线程?

在主线程上调用的方法是
DGifDecompressInput
DGifDecompressLine
copyImageBlockSetGIF

问题是当视图被添加到层次结构时会发生 gif 解压缩 - 这应该在主线程上完成

谢谢


grasGendarme 的代码很有用,但请注意 UIImage 是惰性的,在真正需要之前不会解码图像。关键是您必须使用 CGContextDrawImage 在后台线程上强制解压缩。所以使用 UIImage JTImageDecode.h 在后台创建一个未压缩的图像版本,然后将其设置回主线程。


您可以使用 Grand Central Dispatch 和串行队列让所有事情发生在单独的线程上:

1
2
3
4
5
6
7
8
9
10
11
// create the queue that will process your data:
dispatch_queue_t dataProcessQueue = dispatch_queue_create("data process queue", NULL); // the name is there for debugging purposes
    //dispatch to the newly created queue, and do not wait for it to complete
    dispatch_async(dataProcessQueue, ^{
        // load and decode gif
        // ...
        dispatch_async(dispatch_get_main_queue(), ^{
            // put gif in place (UI work always happen on the main queue)
            // ...
    });
});

很高兴看到实际的代码。没有它,我们的帮助是有限的。

也许你可以写一行:

1
[self performSelectorInBackground:@selector(yourBlockingMethod:) withObject:yourObject];

或者修改你的库以在后台线程上解压 GIF,然后在主线程上使用 setNeedsDisplay