简体   繁体   中英

Convert UIView to .png in Swift

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];

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM