【问题标题】:Screenshot showing up blank - Swift屏幕截图显示为空白 - Swift
【发布时间】:2015-04-25 01:31:47
【问题描述】:

您好,我正在制作一款游戏,我在游戏中添加了一个分享按钮。我希望用户能够在一条消息中同时共享一条消息、URL 和屏幕截图。它的共享方面工作正常,除了屏幕截图本身显示为空白之外,一切都显示出来了。这是我用来截屏的代码:

   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)

    println("screenshot")

请帮我解决这个问题,请务必使用 Swift 语言。如果有什么不同,我也会使用 SpriteKit 技术。我是编码新手,所以请非常清楚。非常感谢!

【问题讨论】:

    标签: ios swift uiview sprite-kit screenshot


    【解决方案1】:

    更新:Xcode 8.2.1 • Swift 3.0.2

    您需要将导入语句和此扩展添加到您的游戏场景中:

    import UIKit 
    

    extension UIView {
        var snapshot: UIImage? {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
            defer { UIGraphicsEndImageContext() }
            drawHierarchy(in: bounds, afterScreenUpdates: true)
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    

    let myImage = view?.snapshot
    

    【讨论】:

    【解决方案2】:

    在 WWDC 2015 中,UIVisualEffectView 的新增功能中,一个解决方案被“修饰”用于捕获包含活力标签和模糊的 UIVisualEffectView 的屏幕截图。经常出现的问题是苹果的截图API往往没有捕捉到UIVisualEffect,导致视图截图没有视觉效果。根据 WWDC 2015 的解决方案包括在窗口/屏幕上捕获快照;不幸的是,没有显示示例代码。以下是我自己的实现:

    //create snapshot of the blurView
    let window = UIApplication.sharedApplication().delegate!.window!!
    //capture the entire window into an image
    UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.mainScreen().scale)
    window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true)
    let windowImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //now position the image x/y away from the top-left corner to get the portion we want
    UIGraphicsBeginImageContext(blurView.frame.size)
    windowImage.drawAtPoint(CGPoint(x: -blurView.frame.origin.x, y: -blurView.frame.origin.y))
    let croppedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    //embed image in an imageView, supports transforms.
    let resultImageView = UIImageView(image: croppedImage)
    

    注意:此快照代码仅在调用 ViewDidAppear 后才有效。

    【讨论】: