警报的屏幕截图,iOS,Swift

Screenshot of an alert, iOS, Swift

我在显示警报时截取屏幕截图,这适用于截取屏幕截图,但是当它保存到相机胶卷时,它只截取了警报后面的屏幕,并没有在屏幕截图中包含警报.

可以这样做吗?

下面是我的代码。

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

我认为你需要密钥的完整层window

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

layer.render(in: UIGraphicsGetCurrentContext()!)

您的代码有两个问题。首先,您要在警报完成显示之前立即尝试拍摄快照。您应该在 present 的完成处理程序中调用您的快照函数:

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

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

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