屏幕截图显示为空白 - Swift

Screenshot showing up blank - Swift

你好,我正在制作游戏,我已经在游戏中添加了一个分享按钮。我希望用户能够共享一条消息,URL,并在一个 message.The 共享方面彼此并排截图,它的共享方面工作正常,一切都显示出来,除了屏幕截图本身正在显示空白。这是我用来截图的代码:

   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 技术。我是编码新手,所以请非常清楚。非常感谢!

更新: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

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

//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 后才有效。