我正在用 Swift 构建一个单 View 游戏,我一直在尝试为游戏添加渐变背景。我创建了一个处理所有渐变事物的新类,但是当我将它添加到场景中的背景时,它会显示在所有其他元素之上,而不是在它所属的位置后面。
这是我写的。它从我编写的单独类中获取颜色值。
let background = CAGradientLayer().turquoiseColor()
background.frame = (self.view?.bounds)!
self.view?.layer.insertSublayer(background, atIndex: 0)
知道为什么要添加到顶部吗?
最佳答案
不要尝试将其添加为子层。将渐变渲染到图像并将该图像设置为 SKSpriteNode 的纹理,然后将该节点添加到您的场景例如:
override func didMoveToView(view: SKView) {
let size = CGSize(width: (self.view?.bounds.width)!,height: (self.view?.bounds.height)!)
UIGraphicsBeginImageContextWithOptions(size, true, 1.0)
let context = UIGraphicsGetCurrentContext()
let gradient = CAGradientLayer().turquoiseColor()
gradient.frame = CGRect(origin: CGPointZero, size: size)
gradient.renderInContext(context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let texture = SKTexture(image:image)
let node = SKSpriteNode(texture:texture)
node.anchorPoint = CGPointZero
node.zPosition = -10.0
self.addChild(node)
}
关于swift - 如何将渐变背景添加到所有其他元素后面的 Swift 播放场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039445/