【问题标题】:SwiftUI tint for image but preserving Black and WhiteSwiftUI 为图像着色但保留黑白
【发布时间】:2020-07-31 16:35:59
【问题描述】:

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

对于 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)" 直接生成灰度图。

【问题讨论】:

    标签: colors swiftui tint


    【解决方案1】:

    你可以继续使用你的扩展,比如

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

    【讨论】:

    • 我知道如何使用扩展,但它是用于 UIImages 的,我需要它来代替 SwiftUI 中的图像。
    • Image 在 SwiftUI 中不是模型 - 它是 一个视图 ≡ UIImageView
    【解决方案2】:

    我在寻找错误的关键字。

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

    请看下面的例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多