Safe way to render UIVIew to an image on backgroun

2019-01-19 02:55发布

问题:

I'm creating small tile images to be stored on disk and displayed to the user. Here is my current process for doing this:

  1. Create a viewcontroller that represents the UI I want to show onscreen
  2. Get the view from the viewcontroller and render an image from it
  3. Save it to disk and display it onscreen later

I am crashing when I attempt to access the view of the viewcontroller. When I tried to research this online, I am getting conflicting results on whether it is safe to create the view in the background. I'm reading that the UIGraphicsGetCurrentContext call should be thread safe, but maybe not accessing the UIView on a background thread? I'm writing the app for iOS 4 and above. Here is the code I'm using (tile is the viewcontroller):

CGSize size = CGSizeMake(20.0f, 30.0f);
UIGraphicsBeginImageContext(size);
[tile.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();           
UIGraphicsEndImageContext();

The crash occurs when trying to access the .view property on the tile (EXC_BAD_ACCESS). The whole point is to render the view to an image in the background to prevent locking up the UI because there are a lot of tiles to process.

Is there a safe way to do this?

回答1:

I've never tried what you described, and I don't like being the bearer of bad news, but taken from Apple's documentation.

Note: For the most part, UIKit classes should be used only from an application’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application’s user interface in any way.

Of course, they conveniently say "For the most part", so that leaves some wiggle room.