简体   繁体   English

Swift 3(SpriteKit):从节点树创建纹理

[英]Swift 3 (SpriteKit): Create a texture from a node tree

I have been trying to render a node tree into an SKTexture as a possible solution to another question here . 我一直在尝试将节点树渲染为SKTexture作为此处另一个问题的可能解决方案。 I tried searching for an answer to this, and I came across one of Apple's Developer pages (view it here ). 我试图寻找答案,然后遇到了Apple开发人员页面之一( 在此处查看 )。 It says the command which converts a node tree into an SKTexture is this: 它说将节点树转换为SKTexture的命令是这样的:

func texture(from node: SKNode) -> SKTexture?

Although, the code is incomplete since there is no code which executes the conversion of a node tree to an SKTexture . 虽然,代码是不完整的,因为没有代码可以执行将节点树转换为SKTexture Am I doing something wrong or what is the complete code that I should use to render a node tree into an SKTexture . 我是在做错什么,还是将节点树渲染为SKTexture时应使用的完整代码是什么?

Thanks for any advice, help, and answers! 感谢您的任何建议,帮助和解答!

texture(from:) is an instance method of SKView that takes a node (with zero or more children) as a parameter and returns an optional SKTexture . texture(from:)SKView的实例方法,该方法将一个节点(具有零个或多个子节点)作为参数,并返回可选的SKTexture Since the returned value is an optional, you'll need to unwrap it before using it. 由于返回的值是可选的,因此在使用它之前,需要先将其解包。

From didMove(to:) , you can use the view parameter to create a texture didMove(to:) ,您可以使用view参数创建纹理

if let texture = view.texture(from: node) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}

From other methods in the SKScene subclass, use optional chaining SKScene子类中的其他方法中,使用可选链接

if let texture = self.view?.texture(from: node) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}

You can also render the portion of the node-tree's contents inside of a rectangle with 您还可以使用以下命令在矩形内部渲染节点树内容的一部分:

let rect = CGRect(x:-width/2, y:-height/2, width:width, height:height)
if let texture = self.view?.texture(from: node, crop: rect) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM