4

How do I convert a UIView to an image. I found this convert uiview to .png image but I'm not to familiar with Objective-C. I took a stab at translating this to Swift but it didn't go so well. could any help?

UIGraphicsBeginImageContext(myView.frame.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data=UIImagePNGRepresentation(viewImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strPath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
[data writeToFile:strPath atomically:YES];
Community
  • 1
  • 1
Pablo Picasso
  • 251
  • 1
  • 4
  • 13

2 Answers2

13

Try this:

UIGraphicsBeginImageContextWithOptions(myView.layer.frame.size, false, scale)
myView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let data = UIImagePNGRepresentation(viewImage)
let documentsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let writePath = documentsDir.stringByAppendingPathComponent("myimage.png")
data.writeToFile(writePath, atomically:true)
Ben Packard
  • 26,102
  • 25
  • 102
  • 183
Andrea
  • 26,120
  • 10
  • 85
  • 131
1

Swift 5 version:

UIGraphicsBeginImageContextWithOptions(myView.layer.frame.size, false, 1) // 1 = scale
myView.layer.render(in: UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let writePath = documentsDir.appendingPathComponent("Image.png")
try! viewImage!.pngData()!.write(to: writePath)
print("Saved image to:" writePath)
jacksoor
  • 353
  • 1
  • 12