以编程方式创建 SKTileDefinition

Programmatically creating an SKTileDefinition

我已经用头撞墙好几个小时了。我正在尝试使用 CIFilter 修改我的应用程序内的纹理,然后将该新纹理用作新 SKTileDefinition 的一部分以重新着色我的地图上的图块。 下面的函数找到玩家 "own" 的图块并尝试通过将 SKTileDefinition 更改为 coloredDefinition.

来重新着色它们
  func updateMapTileColoration(for players: Array<Player>){
    for player in players {
        for row in 0..<mainBoardMap!.numberOfRows {
            for col in 0..<mainBoardMap!.numberOfColumns {
                let rowReal = mainBoardMap!.numberOfRows - 1 - row
                if player.crownLocations!.contains(CGPoint(x: row, y: col)) {
                    if let tile = mainBoardMap!.tileDefinition(atColumn: col, row: rowReal) {
                        let coloredDefinition = colorizeTile(tile: tile, into: player.color!)
                        print(coloredDefinition.name)
                        mainBoardMap!.tileSet.tileGroups[4].rules[0].tileDefinitions.append(coloredDefinition)
                        mainBoardMap!.setTileGroup(crownGroup!, andTileDefinition: crownGroup!.rules[0].tileDefinitions[1], forColumn: col, row: rowReal)
                    }
                }
            }
        }
    }

这里是实际应用 CIFilter 的函数:colorizeTile

func colorizeTile(tile: SKTileDefinition, into color: UIColor) -> SKTileDefinition{
        let texture = tile.textures[0]

        let colorationFilter = CIFilter(name: "CIColorMonochrome")
        colorationFilter!.setValue(CIImage(cgImage: texture.cgImage()), forKey: kCIInputImageKey)
        colorationFilter!.setValue(CIColor(cgColor: color.cgColor), forKey: "inputColor")
        colorationFilter!.setValue(0.25, forKey: "inputIntensity")
        let coloredTexture = texture.applying(colorationFilter!)

        let newDefinition = SKTileDefinition(texture: texture)
        newDefinition.textures[0] = coloredTexture
        newDefinition.name = "meow"

        return newDefinition
    }

我希望能得到任何帮助来弄清楚为什么我不能像我想做的那样更改 tileDefinition。能够定义一个新的 TileDefinition 并将其添加到 tileGroup,然后将 tile 组设置为特定的 tile 定义,这在直觉上似乎是正确的。但是,这会导致出现空白图块...

有什么指点吗?

在尝试了很多东西后,我终于弄清楚出了什么问题。瓷砖定义未正确创建,因为我从未真正绘制过新纹理。据我了解,CIImage 不是绘制的纹理,它只是一个配方,我们需要一个上下文来绘制纹理。进行此更改后,正确创建了 SKTileDefinition。问题不在我认为的地方,所以我有点二手回答这个问题。我创建 SKTileDefinition 的方法是正确的。

   if drawContext == nil{
        drawContext = CIContext()
    }

    let texture = tile.textures[0]

    let colorationFilter = CIFilter(name: "CIColorMonochrome")
    colorationFilter!.setValue(CIImage(cgImage: texture.cgImage()), forKey: kCIInputImageKey)
    colorationFilter!.setValue(CIColor(cgColor: color.cgColor), forKey: "inputColor")
    colorationFilter!.setValue(0.75, forKey: "inputIntensity")

    let result = colorationFilter!.outputImage!
    let output = drawContext!.createCGImage(result, from: result.extent)
    let coloredTexture = SKTexture(cgImage: output!)

    let newDefinition = SKTileDefinition(texture: texture)
    newDefinition.textures[0] = coloredTexture
    newDefinition.name = "meow"