简体   繁体   English

通过缓存异步加载本地UIImage

[英]Load local UIImage asynchronously with caching

UIScrollViewController UIScrollViewController

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

I have a UIScrollViewController which has several subviews. 我有一个UIScrollViewController ,其中包含几个子视图。 Every subview contains a UIImageview , when scrolling the UIImageView , pages on either side of current page will be loaded using 每个子视图都包含一个UIImageview ,滚动UIImageView ,将使用以下方式加载当前页面两侧的页面:

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

But when the local image file becomes really big (>2MB), the scrolling becomes very influent amd gets stuck. 但是,当本地图像文件变得很大(> 2MB)时,滚动变得非常有影响,并且卡住了。

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. 您可以在另一个线程中异步加载图像,或者如果您仅支持高于4的iOS,则很容易使用块来执行它。

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. 最好创建带有“虚拟”或“旋转器”的UIImageViews添加到滚动视图,然后在用户交互停止(通过委托方法检测到)时,可以重新加载可见的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). 当用户滚动时,最好为所需的图像加载和缓存UIImage对象(例如,将它们存储在数组或字典中)。

  • Scale the UIImage content to fit the UIImageView frame inside ScrollView. 缩放UIImage内容以适合ScrollView中的UIImageView框架。 That way during rendering time, UIImage will not 'autoscale' the provided image, so it will be faster. 这样,在渲染期间,UIImage不会“自动缩放”所提供的图像,因此会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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