你必须设置colorBlendFactor
精灵。
func makeSprite(symbolName: String) -> SKSpriteNode {
let image = Image(systemName: symbolName)
// Thanks Oskar!
// https://stackoverflow.com/a/69315037/1610473
// See my adapted version of his code further down; I
// think you won't need it if you're on iOS, meaning
// using UIImage, but that's all black magic to me.
let renderedByOskar = image.renderAsImage()!
let texture = SKTexture(image: renderedByOskar)
let sprite = SKSpriteNode(texture: texture)
sprite.color = .green
sprite.colorBlendFactor = 1 // <-- This
return sprite
}
一个绿色符号,多亏了黑魔法:
非常感谢Oskar的渲染扩展,使我能够在 macOS 上执行此操作,这意味着,无需UIImage
:
class NoInsetHostingView<V>: NSHostingView<V> where V: View {
override var safeAreaInsets: NSEdgeInsets {
return .init()
}
}
extension Image {
func renderAsImage() -> NSImage? {
let view = NoInsetHostingView(rootView: self)
view.setFrameSize(view.fittingSize)
return view.bitmapImage()
}
}
public extension NSView {
func bitmapImage() -> NSImage? {
guard let rep = bitmapImageRepForCachingDisplay(in: bounds) else {
return nil
}
cacheDisplay(in: bounds, to: rep)
guard let cgImage = rep.cgImage else {
return nil
}
return NSImage(cgImage: cgImage, size: bounds.size)
}
}