SwiftUI 为图像着色但保留黑白

SwiftUI tint for image but preserving Black and White

我需要改变图像中的颜色,例如从灰色到绿色。但是只有不是白色的部分and/or黑色...

对于 UIKit,我有一个方便的扩展:

     // colorize image with given tint color
    // this is similar to Photoshop's "Color" layer blend mode
    // this is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved
    // white will stay white and black will stay black as the lightness of the image is preserved
    func tint(tintColor: UIColor) -> UIImage {
        
        return modifiedImage { context, rect in
            // draw black background - workaround to preserve color of partially transparent pixels
            context.setBlendMode(.normal)
            UIColor.black.setFill()
            context.fill(rect)
            
            // draw original image
            context.setBlendMode(.normal)
            context.draw(self.cgImage!, in: rect)
            
            // tint image (loosing alpha) - the luminosity of the original image is preserved
            context.setBlendMode(.color)
            tintColor.setFill()
            context.fill(rect)
            
            // mask by alpha values of original image
            context.setBlendMode(.destinationIn)
            context.draw(self.cgImage!, in: rect)
        }
    }

有什么方法可以使用 SwiftUI 中的色调选项生成相同的功能?

".colorMultiply" 颜色也是白色。

".saturation(0.5)"直接生成灰度图

您可以继续使用您的扩展程序,喜欢

var body: some View {
   Image(uiImage: UIImage(named: "some")!.tint(tintColor: UIColor.red))
}

我找错关键字了。

在 SwiftUI 中执行此操作的实际方法是 hueRotation! 它只适用于彩色图像,而不适用于灰度图像。

参见下面的示例:

   Color.blue
       .hueRotation(.degrees(-45.0))