我已经用工厂解决了我的问题。
阅读更多关于如何制造工厂的信息,来自BenMobile's 耐心和清晰的表达,这里:Factory creation and use for making Sprites and Shapes
模糊SKTexture 或SKSpriteNode 会出现空间不足的问题。模糊/发光超出了精灵的边缘。为了解决这个问题,在下面,您将看到我创建了一个“成帧器”对象。这只是一个空的SKSpriteNode,它是要模糊的纹理大小的两倍。要模糊的纹理作为子对象添加到此“成帧器”对象。
不管这有多骇人听闻,它都能正常工作;)
在静态工厂类文件中:
import SpriteKit
class Factory {
private static let view:SKView = SKView() // the magic. This is the rendering space
static func makeShadow(from source: SKTexture, rgb: SKColor, a: CGFloat) -> SKSpriteNode {
let shadowNode = SKSpriteNode(texture: source)
shadowNode.colorBlendFactor = 0.5 // near 1 makes following line more effective
shadowNode.color = SKColor.gray // makes for a darker shadow. White for "glow" shadow
let textureSize = source.size()
let doubleTextureSize = CGSize(width: textureSize.width * 2, height: textureSize.height * 2)
let framer = SKSpriteNode(color: UIColor.clear, size: doubleTextureSize)
framer.addChild(shadowNode)
let blurAmount = 10
let filter = CIFilter(name: "CIGaussianBlur")
filter?.setValue(blurAmount, forKey: kCIInputRadiusKey)
let fxNode = SKEffectNode()
fxNode.filter = filter
fxNode.blendMode = .alpha
fxNode.addChild(framer)
fxNode.shouldRasterize = true
let tex = view.texture(from: fxNode) // ‘view’ refers to the magic first line
let shadow = SKSpriteNode(texture: tex) //WHOOPEE!!! TEXTURE!!!
shadow.colorBlendFactor = 0.5
shadow.color = rgb
shadow.alpha = a
shadow.zPosition = -1
return shadow
}
}
在您可以访问要为其制作阴影或发光纹理的 Sprite 的任何地方:
shadowSprite = Factory.makeShadow(from: button, rgb: myColor, a: 0.33)
shadowSprite.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 5)
addChild(shadowSprite)
-
button 是要赋予阴影的按钮的纹理。 a: 是一个 alpha 设置(实际上是透明度级别,0.0 到 1.0,其中 1.0 是完全不透明的),这个值越低阴影越亮。
该定位用于将阴影稍微放在按钮下方,因此看起来光线从顶部射入,将阴影向下投射到背景上。