当我尝试在 Swift 中以编程方式截取我的应用程序的屏幕截图时,为什么屏幕截图只显示白色?
Why does the screenshot show just white when I'm trying to take a screenshot of my app programmatically in Swift?
在我的应用程序中,我有一个装有相机的视图。我想截取这个拿着相机的视图。但是,当我使用以下代码执行此操作时:
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)
}
在我的应用程序中,我有一个装有相机的视图。我想截取这个拿着相机的视图。但是,当我使用以下代码执行此操作时:
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)
}