I am trying to convert my UIView into UIImage using below code.
+ (UIImage *) imageWithView:(UIView *)view{
float scale = 1.0f;
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
view.layer.contents = nil;
return img;
}
There are two problem with this code.
1. When I run this code in background thread(!mainThread)
I faced memory leak problem when renderInContext is called in background thread.
2. When I run this code on Main thread
There is no memory leak but on iPad 3 I am facing some performance issue (my UI hangs when this method is called) while creating image from UIView. As I need to call this function more than 5 times in a seconds so UI hangs gives very bad user experience.
Please guide me if I am doing some thing wrong here?
I think that issue 1 is related to the fact that
UIKitis not thread safe and its use will lead to all kinds of side effects.If you have performance issue like you are describing, the only path forward I see is directly using CoreGraphics (not UIKit) on a secondary thread.
You might try something like this, as a start:
As you see, this is pretty more complex than the
UIKitway, but it can be run on a secondary thread (provided you find a way to pass theoutputImageback to your UI thread which is not shown).