【发布时间】:2017-10-29 12:47:29
【问题描述】:
我有一个变量var image = SKSpriteNode(imageNamed: "image"),它是一个大纲。我想用颜色填充图像,但不知道必要的代码。有人能提供解决方案吗?
【问题讨论】:
-
不知道为什么投反对票。
标签: ios swift graphics colors sprite-kit
我有一个变量var image = SKSpriteNode(imageNamed: "image"),它是一个大纲。我想用颜色填充图像,但不知道必要的代码。有人能提供解决方案吗?
【问题讨论】:
标签: ios swift graphics colors sprite-kit
这是另一种方法,为方便起见,将其包裹在 SpriteNode 扩展中:
extension SKSpriteNode {
func fromFilledPath(path: CGPath, color: SKColor) -> SKSpriteNode {
let shape = SKShapeNode(path: path)
shape.fillColor = color
return SKSpriteNode(texture: SKView().texture(from:shape))
}
}
class GameScene: SKScene {
let myPathSprite = SKSpriteNode.fromFilledPath(~~~~)
}
【讨论】:
您不能对 SKSpriteNode 或图像执行此操作。您需要做的是使用UIBezierPath 或CGPath 创建轮廓路径,然后创建一个旨在填充路径区域的上下文。
然后您可以返回生成的图像并将其附加到精灵。
func fillInPath(path: CGPath, color: UIColor) -> UIImage?
{
let size = path.boundingBoxOfPath()
UIGraphicsBeginImageContext( size)
guard let context = UIGraphicsGetCurrentContext()
else
{
UIGraphicsEndImageContext()
return nil
}
context.addPath(path) // the path of your outline
context.clip()
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIImage(cgImage:context.makeImage()!)
UIGraphicsEndImageContext()
return image
}
【讨论】: