在iPhone应用程序中从磁盘加载图像很慢 [英] loading images from disk in iPhone app is slow
问题描述
在我的iPhone应用程序中,我正在使用iPhone的相机拍摄照片并将其保存到磁盘(应用程序的文档文件夹)。这是我如何保存它:
In my iPhone app, I am using the iPhone's camera to take a photo and save it do disk (the application's documents folder). This is how i save it:
[UIImageJPEGRepresentation(photoTaken, 0.0) writeToFile:jpegPath atomically:YES];
使用压缩程度最高,我认为从磁盘读取图像会很快。但它不是!我在我的一个视图中使用图像作为按钮的背景图像。我像这样加载它:
Using the most compression, I figured reading the image from disk would be quick. But its not! I use the image as the background image for a button in one of my views. I load it like this:
[self.frontButton setBackgroundImage:[UIImage imageWithContentsOfFile:frontPath] forState:UIControlStateNormal];
当我使用此按钮导航到视图时,它很慢且不连贯。我该如何解决这个问题?
When I navigate to the view with this button, it is slow and choppy. How do I fix this?
推荐答案
+ imageWithContentsOfFile:
是同步的,所以主线程上的UI被磁盘操作中的图像加载阻塞并导致不稳定。解决方案是使用从磁盘异步加载文件的方法。您也可以在后台线程中执行此操作。这可以通过在 dispatch_async()
中包装 + imageWithContentsOfFile:
,然后嵌套包装
,因为需要在主线程上运行UIKit方法。如果您希望在加载视图后立即显示图像,则需要从磁盘预先缓存图像,以便在视图出现时立即在内存中。 -setBackgroundImage:
的主队列上的> dispatch_async()
+imageWithContentsOfFile:
is synchronous, so the UI on your main thread is being blocked by the image loading from disk operation and causing the choppiness. The solution is to use a method that loads the file asynchronously from disk. You could also do this in a background thread. This can be done easily by wrapping the +imageWithContentsOfFile:
in dispatch_async()
, then a nested dispatch_async()
on the main queue that wraps -setBackgroundImage:
since UIKit methods need to be run on the main thread. If you want the image to appear immediately after the view loads, you'll need to pre-cache the image from disk so it's in-memory immediately when the view appears.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
UIImage *image = [UIImage imageWithContentsOfFile:frontPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self.frontButton setBackgroundImage:image forState:UIControlStateNormal];
});
});
另外,如果按钮图像出现渐变,请考虑使用以下属性来确保图像从磁盘加载的文件很小:
As an aside, if the button image happens a gradient, consider using the following properties to ensure the image file loaded from disk is tiny:
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets
或(不建议使用,仅在您需要支持iOS 4.x时使用):
or (deprecated, only use if you need to support iOS 4.x):
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
这篇关于在iPhone应用程序中从磁盘加载图像很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!