以编程方式截取图像

时间:2018-04-16 19:57:21

标签: ios swift

我一直处在这样一种情况,即我希望我的代码能够截取屏幕截图,但只是中间部分。

    @IBAction func savePhoto(_ sender: UIButton) {

    // Does not go into program
    let size = CGSize(width: view.frame.size.width, height: view.frame.size.height)

    UIGraphicsBeginImageContextWithOptions(CGSize(width:1024.0,height: 1024.0), false, UIScreen.main.scale)


    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil)

    }

我确实尝试过它,当它截图时它会使它成为1024x1024而且我认为这样可行,但事实并非如此。

1 个答案:

答案 0 :(得分:0)

试试这个,它对我有用。 希望,这很有帮助。

@IBAction func savePhoto(_ sender: UIButton) {

            UIGraphicsBeginImageContextWithOptions(CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height - 100), false, 0.0)
            self.view.drawHierarchy(in: CGRect(x: 0, y: 0, width: 1024.0, height: 1024.0), afterScreenUpdates: true)
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

            }
            UIGraphicsEndImageContext();

        }
相关问题