UIImage decompression causing scrolling lag

后端 未结 3 1409
执念已碎
执念已碎 2021-01-30 07:26

I have this app with a full screen tableView that displays a bunch of tiny images. Those images are pulled from the web, processed on a background thread, and then saved to disk

3条回答
  •  后悔当初
    2021-01-30 08:05

    Jason's tip about pre-drawing the image to decompress it is the key, but you'll get even better performance by copying the whole image and discarding the original.

    Images created at runtime on iOS seem to be better optimised for drawing than ones that have been loaded from a file, even after you've forced them to decompress. For that reason, you should load like this (it's also a good idea to put the decompressed image into an NSCache so you don't have to keep reloading it):

    - (void)loadImageWithPath:(NSString *)path block:(void(^)(UIImage *image))block
    {
        static NSCache *cache = nil;
        if (!cache)
        {
            cache = [[NSCache alloc] init];
        }
    
        //check cache first
        UIImage *image = [cache objectForKey:path];
        if (image)
        {
            block(image);
            return;
        }
    
        //switch to background thread
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    
            //load image
            UIImage *image = [UIImage imageWithContentsOfFile:path];
    
            //redraw image using device context
            UIGraphicsBeginImageContextWithOptions(image.size, YES, 0);
            [image drawAtPoint:CGPointZero];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
    
            //back to main thread
            dispatch_async(dispatch_get_main_queue(), ^{
    
                //cache the image
                [cache setObject:image forKey:path];
    
                //return the image
                block(image);
            });
        });
    }
    

提交回复
热议问题