【问题标题】:How do I screenshot a uiview without adding it to the subview?如何在不将其添加到子视图的情况下截取 uiview?
【发布时间】:2017-04-07 08:40:10
【问题描述】:

我在父视图上有多个子视图,我需要将 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

获取快照图像

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
    }
}

【问题讨论】:

标签: ios swift


【解决方案1】:

首先,您的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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多