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
I created this extension for save a screen shot from UIView
extension UIView {
func saveImageFromView(path path:String) {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
}}
call:
let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
reportView.saveImageFromView(path: pathImage)
If you want to create a png must change:
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
by
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
I think you may want renderInContext
, not drawInContext
. 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.
-(UIImage *)convertViewToImage
{
UIGraphicsBeginImageContext(self.bounds.size);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
I have created usable extension for UIView to take screenshot in Swift:
extension UIView{
var screenshot: UIImage{
UIGraphicsBeginImageContext(self.bounds.size);
let context = UIGraphicsGetCurrentContext();
self.layer.renderInContext(context)
let screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenShot
}
}
To use it just type:
let screenshot = view.screenshot
CGImageRef UIGetScreenImage();
Apple now allows us to use it in a public application, even though it's a private API
There is new API from iOS 10
extension UIView {
func makeScreenshot() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
return renderer.image { (context) in
self.layer.render(in: context.cgContext)
}
}
}