IOS的雪碧套件screengrab?
我试图获得一个SKScene的视图的屏幕抓取。 我正在使用的技术是:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
这对于普通的UIViews来说效果很好,但是无论如何它忽略了SKScene中的所有精灵。
我不确定这是否是一个错误,或者Sprite Kit的渲染是否与UIGraphics分离。
问题:如何在使用UIViews的方式看起来不适用于Sprite Kit,或者有人使用Sprite Kit使用UIGraphics上下文时,如何获得SKScene的屏幕截图?
你几乎可以拥有它,但问题正如上面的评论中所解释的那样。 如果你想捕捉SKScene
内容,请尝试这样的事情:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale); [self.view drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
解决的办法是基本上使用新的方法drawViewHierarchyInRect:afterScreenUpdates
代替,这是我们现在最好的; 注意,它不是很快,所以这样做实时将不会很漂亮。
作为一个更快的select,你可以在textureFromNode
上使用textureFromNode
方法,它将视图的图像作为SKTexture
。 简单地通过SKScene
作为参数:
let texture = skView.textureFromNode(scene)
或者捕捉部分场景:
let texture = skView.textureFromNode(scene, crop: cropRect)
// 1:从“someNode”获取纹理
let texture = skView.textureFromNode(someNode)
// 2:从节点纹理获取UIImage
let image = UIImage(cgImage: texture!.cgImage())
Swift的解决scheme:
func getScreenshot(scene: SKScene, duration:TimeInterval = 0.0001, completion:((_ txt:SKTexture) -> Void)?) { let action = SKAction.run { let bounds = scene.view?.bounds var image = UIImage() UIGraphicsBeginImageContextWithOptions(bounds!.size, true, UIScreen.main.scale) scene.view?.drawHierarchy(in: bounds!, afterScreenUpdates: true) if let screenshot = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext() image = screenshot } else { assertionFailure("Unable to make a screenshot for the scene \(type(of:scene))") } completion!(SKTexture(image: image)) } let wait = SKAction.wait(forDuration: duration) let seq = SKAction.sequence([wait,action]) scene.run(seq,withKey:"getScreenshot") }
用法 :
getScreenshot(scene: self, completion:{ (txt) -> Void in let thumbNode = SKSpriteNode(texture: txt, size:CGSize(width:300,height:224)) // do whatever you want with your screenshot.. }