【问题标题】:Fll an asset with colour用颜色填充资产
【发布时间】:2017-10-29 12:47:29
【问题描述】:

我有一个变量var image = SKSpriteNode(imageNamed: "image"),它是一个大纲。我想用颜色填充图像,但不知道必要的代码。有人能提供解决方案吗?

【问题讨论】:

  • 不知道为什么投反对票。

标签: ios swift graphics colors sprite-kit


【解决方案1】:

这是另一种方法,为方便起见,将其包裹在 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(~~~~)

}

【讨论】:

    【解决方案2】:

    您不能对 SKSpriteNode 或图像执行此操作。您需要做的是使用UIBezierPathCGPath 创建轮廓路径,然后创建一个旨在填充路径区域的上下文。

    然后您可以返回生成的图像并将其附加到精灵。

    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            
    }
    

    【讨论】:

    • 将其转换为 skshape 会不会更容易/更高效?
    • 不确定哪个更有效,但上下文为您提供了更多选择
    猜你喜欢
    • 2015-12-31
    • 2012-04-24
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2014-10-27
    • 2018-12-12
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多