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: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:indispatch_async(), then a nesteddispatch_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.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:
or (deprecated, only use if you need to support iOS 4.x):