【问题标题】:Display an UIImage in SwitfUI is dark - Apple Watch在 SwitfUI 中显示 UIImage 是暗的 - Apple Watch
【发布时间】:2020-05-29 09:39:04
【问题描述】:

我不明白为什么 Apple Watch 模拟器上没有出现汽车系统名称图像。 (黑色)

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(屏幕全黑,就像视图中没有添加任何内容一样)

【问题讨论】:

    标签: swift swiftui watchkit apple-watch watchos


    【解决方案1】:

    我想应该是

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

    或者...如果你喜欢UIImage,同样的结果

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

    【讨论】:

    • @FirsfNameLastname 出于好奇,为什么是 UIImage?跨 UIKit 目标共享?
    【解决方案2】:

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

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

    其中 maskWithColor 来自https://stackoverflow.com/a/36591030/12893419

    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
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多