屏幕截图显示空白 - Swift

时间:2015-04-25 01:31:48

标签: ios swift uiview sprite-kit screenshot

嗨,我正在制作一款游戏,并为游戏添加了一个分享按钮。我希望用户能够在一条消息中彼此共享消息,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技术,如果它有所作为。我是编码的新手,所以请非常清楚。非常感谢你!

2 个答案:

答案 0 :(得分:11)

更新: Xcode 8.2.1•Swift 3.0.2

您需要将import语句和此扩展名添加到游戏场景中:

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

答案 1 :(得分:5)

在WWDC 2015中,UIVisualEffectView的新功能,一个解决方案被“掩盖”,用于捕获包含活力标签和模糊的UIVisualEffectView的屏幕截图。经常出现的问题是,Apple的截图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后,此快照代码才会起作用。