在我的应用程序上,我有一个装有相机的视图。我想拍摄一张包含相机的视图的屏幕截图。但是,当我使用以下代码执行此操作时:
let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)
保存到照片的屏幕截图仅为空白,并且不显示相机视图。
最佳答案
Render and capture名为UIView
的view
:
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
记住
UIWindow
也是一个视图。您可以使用以下功能在模拟器中进行测试并保存到桌面:
public func saveImageToDesktop(image : UIImage, name : String)
{
let basePath = NSString(string: "~/Desktop").stringByExpandingTildeInPath
let path = "\(basePath)/\(name).png"
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
}
关于ios - 当我尝试在Swift中以编程方式拍摄应用程序的屏幕截图时,为什么屏幕截图仅显示为白色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33316189/