在 Switf 中显示 UIImage UI is dark - Apple Watch

Display an UIImage in SwitfUI is dark - Apple Watch

我不明白为什么 car systemName 图像没有出现在 Apple Watch Simulator 上。 (它是黑色的)

import SwiftUI
struct ContentView: View {
    var body: some View {
        Image(uiImage: UIImage(systemName: "car")!)
    }
}

struct preview : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Click here to see how it looks(屏幕全黑,就像什么都没加一样)

我想应该是

struct ContentView: View {
    var body: some View {
        Image(systemName: "car") // < Native SwiftUI
    }
}

或者...如果您喜欢UIImage,结果与

相同
Image(uiImage: UIImage(systemName: "car")!).colorInvert()

一个解决方案是将 UIImage 颜色设置为白色,这样它就会可见

Image(uiImage: UIImage(systemName: "car")!.maskWithColor(color: .white)!)

其中 maskWithColor 来自

extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }

}