截图显示空白 – 斯威夫特
嗨,我正在做一个游戏,我已经添加了一个分享button的游戏。 我希望用户能够在一条消息中共享消息,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技术,如果这有所作为。 我是新来的编码,所以请非常清楚。 非常感谢你!
更新: 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中有什么新东西,一个解决scheme是“掩盖”捕捉包含活力标签和模糊的UIVisualEffectView的屏幕截图。 经常出现的问题是,苹果的屏幕截图API往往不捕获UIVisualEffect,导致视图的屏幕截图没有视觉效果。 根据WWDC 2015的解决scheme涉及在窗口/屏幕捕获快照; 不幸的是,示例代码没有显示。 以下是我自己的实现:
//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被调用后才能使用。