amleszk
amleszk

Reputation: 6290

Avoid image decompression blocking the main thread

I have some code to display an animated GIF image using a UIImageView, here: https://github.com/amleszk/GifBlocking

It works well for 99% of cases, although there is an issue with a certain type of GIF image, An example can be found here: http://i.imgur.com/mbImw.gif

This gif receives 101 images fine, then blocks the main thread when it comes time to display the UIImageView containing the animated images. Its fine to decompress the gif if it has compression, but how would i stop this blocking the main thread?

The methods that get invoked on the main thread are DGifDecompressInput DGifDecompressLine copyImageBlockSetGIF

the problem is the gif decompression happens when the view gets added to the heirarchy - which should be done on the main thread

Thanks

Upvotes: 3

Views: 1359

Answers (3)

Jano
Jano

Reputation: 63667

grasGendarme's code is useful, but note that UIImage is lazy and won't decode the image until it is really needed. The key is that you have to force decompression on a background thread using CGContextDrawImage. So use UIImage+JTImageDecode.h to create an uncompressed image version on the background, then set it back to the main thread.

Upvotes: 6

toasted_flakes
toasted_flakes

Reputation: 2509

You could make everything happen on a separate thread using Grand Central Dispatch and serial queues:

// 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)
            // ...
    });
});

Upvotes: 2

Ilea Cristian
Ilea Cristian

Reputation: 5831

It would be great to see the actual code. Without that, our help is limited.

Maybe you can put a line:

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

Or modify your library to decompress the GIF on a background thread, then use setNeedsDisplay on the main thread.

Upvotes: 2

Related Questions