如何解决在 Swift 中为 SKSprite 添加渐变
尝试在 Swift 中为 Sprite 添加纹理。
找到了这个解决方案,看起来不错。
https://maximbilan.medium.com/sprite-kit-gradient-1ffb7ec35c6a
写于 2016 年,所以从那时起不得不修复一些语法更改,但卡在最后一行。
public enum GradientDirection {
case Up
case Left
case UpLeft
case UpRight
}
public extension SKTexture {
convenience init(size: CGSize,color1: CIColor,color2: CIColor,direction: GradientDirection = .Up) {
let context = CIContext(options: nil)
let filter = CIFilter(name: "CILinearGradient")
var startVector: CIVector
var endVector: CIVector
filter!.setDefaults()
switch direction {
case .Up:
startVector = CIVector(x: size.width * 0.5,y: 0)
endVector = CIVector(x: size.width * 0.5,y: size.height)
case .Left:
startVector = CIVector(x: size.width,y: size.height * 0.5)
endVector = CIVector(x: 0,y: size.height * 0.5)
case .UpLeft:
startVector = CIVector(x: size.width,y: 0)
endVector = CIVector(x: 0,y: size.height)
case .UpRight:
startVector = CIVector(x: 0,y: 0)
endVector = CIVector(x: size.width,y: size.height)
}
filter!.setValue(startVector,forKey: "inputPoint0")
filter!.setValue(endVector,forKey: "inputPoint1")
filter!.setValue(color1,forKey: "inputColor0")
filter!.setValue(color2,forKey: "inputColor1")
let image = context.createCGImage(filter!.outputimage!,from: CGRect(x: 0,y: 0,width: size.width,height: size.height))!
self(cgImage: image) <- Syntax here wrong??
}
}
self(cgImage: image) 行的语法错误。
你像这样使用它(语法需要从 2016 年开始更新)。
let topColor = CIColor(rgba: "#71B280")
let bottomColor = CIColor(rgba: "#134E5E")
let texture = SKTexture(size: CGSizeMake(200,200),color1: topColor,color2: bottomColor,direction: GradientDirection.Up)
texture.filteringMode = .Nearest
let sprite = SKSpriteNode(texture: texture)
sprite.position = CGPointMake(CGRectGetMidX(frame),CGRectGetMidY(frame))
sprite.size = self.frame.size
addChild(sprite)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。