Todd Lehman
Todd Lehman

Reputation: 2930

Rendering new UIView layer contents on background thread?

I have a whole bunch of rotating animated UIView instances whose contents are set to various CGImage that are all (and by nature need to be) created on-the-fly. It's working great, but image generation is slow (on the order of 1/4 second to 1 second — i.e., unacceptable).

So what I'd like to do is generate a low-resolution approximation very quickly (say, 1/100 second), and set the UIView's CALayer's contents (e.g., view.layer.contents) to that quick low-resolution image, and then immediately spawn a background thread to generate a high-resolution version to eventually replace the low-resolution version as soon as it's ready.

What are some sensible ways to do this?

My thought was that I should use GCD (Grand Central Dispatch) to schedule the background thread, and then use it again to send a message upon completion. If I did it this way, would it make sense to send the new high-resolution replacement image as part of the completion message?

What if I need to cancel the background thread? This would happen if the user pages ahead to a different object, in which case I would have to cancel the current background task and start a new one for a different view. (This will actually be a fairly common occurrence, so I definitely need to handle it.) I don't think I can just kill the background task, because it might be in the middle of handling CGPath, CGGradient, CGImage, etc. objects that would need to be released. What are some ways to set flags from one thread that the other can test? Should I send some sort of "abort" signal from the main thread to the background thread, and then let the background thread abort creation of the image by itself at the most comfortable spot for it?

Upvotes: 1

Views: 1548

Answers (1)

deleted_user
deleted_user

Reputation: 3805

I wouldnt use GCD for this. GCD has problems updating the UI on the callback. If you do this per image it will destroy the performance. Just detach a single thread and realize the high def image serially executign a callback every time one of the images has rendered. Its much simpler and your callbacks to the main thread will display much faster.

For some reason UI updates from GCD dont seem to be very reliable as in way too slow. Not sure why this is.

Upvotes: 1

Related Questions