简体   繁体   中英

Load local UIImage asynchronously with caching

UIScrollViewController

|-----UIImageView1, 2, 3, 4, 5...

I have a UIScrollViewController which has several subviews. Every subview contains a UIImageview , when scrolling the UIImageView , pages on either side of current page will be loaded using

imageView = [[UIImageView alloc] initWithContentsOfFile:fileName];

But when the local image file becomes really big (>2MB), the scrolling becomes very influent amd gets stuck.

Is there a way to avoid this? For example using a cache or doing it asynchronously?

You can load images asynchronously, in another thread, or if you support only iOS higher than 4, it's quite easy to perform it with blocks.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
    UIImageView* imageView = [[[UIImageView alloc] initWithContentsOfFile:fileName]autorelease];       
    dispatch_async(dispatch_get_main_queue(), ^{
        //Maybe correct the frame too
        [self.view addSubview:imageView];
    });
});

If you can't use blocks, you can execute in different thread, but it's a bit more involved.

Anyway, I recommend:

  • Better have created UIImageViews added to the scrollview, with a 'dummy' or 'spinner', then when user interaction stops (detected via delegate method), you can reload the visible imageviews.

  • When user is scrolling, better to load and cache UIImage objects for the images you want, (store them in an array or dictionary for example).

  • Scale the UIImage content to fit the UIImageView frame inside ScrollView. That way during rendering time, UIImage will not 'autoscale' the provided image, so it will be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM