I am wondering how my iPhone app can take a screen shot of a specific UIView
as a UIImage
.
I tried this code but all I get is a blank image.
UIGraphicsBeginImageContext(CGSizeMake(320,480));
CGContextRef context = UIGraphicsGetCurrentContext();
[myUIView.layer drawInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
myUIView
has dimensions 320x480 an it has some sub-views.
What is the correct way to do this?
You need to capture the key window for a screenshot or a UIView. You can do it in Retina Resolution using UIGraphicsBeginImageContextWithOptions and set its scale parameter 0.0f. It always captures in native resolution (retina for iPhone 4 and later).
This one does a full screen screenshot (key window)
This code capture a UIView in native resolution
This saves the UIImage in jpg format with 95% quality in the app's document folder if you need to do that.
you can use following UIView category -
iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.
I implemented a category method on
UIView
to get the view as anUIImage
:It is considerably faster then the existing
renderInContext:
method.Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html
UPDATE FOR SWIFT: An extension that does the same:
UPDATE FOR SWIFT 3
I think you may want
renderInContext
, notdrawInContext
. drawInContext is more a method you would override...Note that it may not work in all views, specifically a year or so ago when I tried to use this with the live camera view it did not work.
iOS7 onwards, we have below default methods :
Calling above method is faster than trying to render the contents of the current view into a bitmap image yourself.
If you want to apply a graphical effect, such as blur, to a snapshot, use the
drawViewHierarchyInRect:afterScreenUpdates:
method instead.https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html
I have created usable extension for UIView to take screenshot in Swift:
To use it just type: