我在父视图上有多个子视图,我需要将uiview转换为uiimage,但只能转换为某些子视图。所以我在视图中添加了一个标签,我需要截取屏幕截图并将其添加到自己的视图中,但是当我尝试截图时,我会看到黑屏。但是,当我使用常规父视图时,我会得到一张包含所有子视图的照片。
let viewPic = UIView()
for subview in self.view.subviews {
if(subview.tag == 6) {
viewPic.addSubview(subview)
}
if(subview.tag == 8) {
viewPic.addSubview(subview)
}
}
let picImage = viewPic.getSnapshotImage() //This is a black screen
getSnapshotImage
extension UIView {
public func getSnapshotImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
let snapshotItem: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return snapshotItem
}
}
答案 0 :(得分:0)
首先,您的viewPic
没有设置帧大小,因此默认值为零帧,这可能会导致问题。
其次,我尝试在我的示例项目中使用您的getSanpshotImage()
,但我总是得到空白图像。
看看演示代码,我可以得到你想要的东西(见截图):
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let viewPic = UIView()
viewPic.frame = self.view.frame
let view1 = UIView()
view1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
view1.backgroundColor = UIColor.red
viewPic.addSubview(view1)
let view2 = UIView()
view2.frame = CGRect(x: 0, y: 200, width: 100, height: 100)
view2.backgroundColor = UIColor.blue
viewPic.addSubview(view2)
let picImage = viewPic.convertToImage() //This is a black screen
print(picImage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIView {
func convertToImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}