Loading image from user interface thread?

How to load an image from a resource in a background thread?

I am currently doing this, and this slows down my interface a bit:

image = [NSData dataWithContentsOfFile:imageName]; 

I would prefer to load it into a background thread.

0
source share
2 answers
 dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_queue_t mainQueue = dispatch_get_main_queue(); dispatch_async(backgroundQueue,^{ // background process image = [NSData dataWithContentsOfFile:imageName]; dispatch_async(mainQueue,^{ // always update GUI from the main thread // uiimageview.image = image.... etc }); }); 
+5
source

you can use CGDataProvider to open CGImage .

for example, you can use CGImageCreateWithPNGDataProvider , and the data provider will reference CFURL . you can use a similar approach for CFData .

then you can use CGImage or hop back to the main thread and create a UIImage .

Finally, you can simply load CFData or NSData from the secondary stream, and then return to the main stream to do something with it.

it can also be noted that UIImage is an immutable type and in some cases uses a cache. if you download the same view multiple times, make sure you do not turn off this optimization.

+3
source

Source: https://habr.com/ru/post/900976/


All Articles