警报,iOS,Swift的屏幕截图

时间:2017-11-09 14:59:44

标签: ios swift screenshot uialertview

当我显示警报时,我正在截取屏幕截图,这可用于截取屏幕截图,但是当它保存到相机胶卷时,它仅捕获警报后面的屏幕,并且未在屏幕截图中包含警报。 / p>

是否可以这样做?

以下是我的代码。

func ScreenShot() {
    //Create the UIImage
    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, 0)
    guard let context = UIGraphicsGetCurrentContext() else { return }
    view.layer.render(in: context)
    guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
    UIGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

在这里打电话。

func alertShow() {

    let alert = UIAlertController(title: "ALERT!!!", message: "Message stuff", preferredStyle: UIAlertControllerStyle.alert)


    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in

        self.performSegue(withIdentifier: "toMainInfoVC", sender: nil)

    }))

    self.present(alert, animated: true, completion: nil)
    ScreenShot()
}

2 个答案:

答案 0 :(得分:2)

我认为您需要关键窗口的完整图层

let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

layer.render(in: UIGraphicsGetCurrentContext()!)

答案 1 :(得分:2)

您的代码存在两个问题。首先,您会在警报完成之前立即尝试拍摄快照。您可以在当前的竞争处理程序中调用快照函数:

self.present(alert, animated: true) { self.ScreenShot() }

其次,您只渲染当前视图,并且警报不是viewcontroller视图的子视图。您想要渲染整个窗口层次结构:

view.window?.layer.render(in: context)