SwiftUI为图像着色但保留黑白

时间:2020-07-31 16:35:59

标签: colors swiftui tint

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

对于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中的tint选项生成相同的功能?

“。colorMultiply”也将颜色设置为白色。

“。saturation(0.5)”直接生成灰度图像。

2 个答案:

答案 0 :(得分:0)

您可以继续使用扩展程序,例如

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

答案 1 :(得分:0)

我在寻找错误的关键字。

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

请参见以下示例:

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