在Swift中把UIView转换为.png[英] Convert UIView to .png in Swift

本文是小编为大家收集整理的关于在Swift中把UIView转换为.png的处理方法,想解了在Swift中把UIView转换为.png的问题怎么解决?在Swift中把UIView转换为.png问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

如何将 UIView 转换为图像.我发现了这个 convert uiview to .png image 但我不熟悉 Objective-C.我尝试将其翻译成 Swift,但效果并不好.有什么帮助吗?

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

推荐答案

试试这个:

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)

本文地址:https://www.itbaoku.cn/post/924612.html

相关标签/搜索