【问题标题】:Why does the screenshot show just white when I'm trying to take a screenshot of my app programmatically in Swift?当我尝试在 Swift 中以编程方式截取我的应用程序的屏幕截图时,为什么屏幕截图显示为白色?
【发布时间】:2015-10-24 08:38:34
【问题描述】:

在我的应用程序中,我有一个装有相机的视图。我想截取这个装有相机的视图的屏幕截图。但是,当我使用以下代码执行此操作时:

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)

保存到照片的屏幕截图只是空白,不显示相机视图。

【问题讨论】:

  • 我相信相机视图不使用CALayer。你必须使用原生的拍照方式。
  • 好的,谢谢,但是当我尝试使用此代码执行此操作时 - var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault) "kCGRenderingIntentDEfault" 有一个错误 "未解析的标识符" 你知道吗如何解决这个问题??

标签: ios swift camera screenshot


【解决方案1】:

Render and capture 一个名为 UIViewview

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多