Pregunta

I'm drawing a view using renderInContext to create a screenshot for storage in core-data.

I'm using this 'standard' code...

UIGraphicsBeginImageContextWithOptions( myview.bounds.size, YES, 0 );

CGContextRef ctx = UIGraphicsGetCurrentContext();
[myview.layer renderInContext:ctx];

UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Originally, I was doing this on the main thread which worked fine. However, as the view and its subviews became more complex (possibly hundreds of subviews with their own draw routines) the UI became too slow. So, I moved the rendering into a background thread.

This works except for the background color of the view 'myview' is black, which isn't what I've set it to...white.

With experimentation, I've noticed that if I pause my background thread for a second or two, the rendering is complete, with my background the required color. This is kind-of-ok but as the view becomes more complex, the pause needs to be longer in order to get the correct image of the view and it's not really correct to have a time delay in which I need to 'up' as the view gets more complex.

Has anyone got any suggestions how to resolve?

¿Fue útil?

Solución

For info purposes, I've managed to fix this.

When I needed to render in the background, I was recreating my view and its subviews programmatically but the main view was not immediately calling drawRect when I called setNeedsDisplay...(of course!). So my background thread sometimes ran before the main view had rendered.

By forcing the view to render itself (with the code below) immediately, I could 'synchronise' everything and get the correct thumbnails.

CALayer *layer = self.layer;
[layer setNeedsDisplay];
[layer displayIfNeeded];

Hope this helps anyone else.

Otros consejos

Alternative:

UIGraphicsBeginImageContextWithOptions(myview.bounds.size, YES, 0);
[myview drawViewHierarchyInRect:_captureView.bounds afterScreenUpdates:YES];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top