colorsswiftuitint

SwiftUI tint for image but preserving Black and White


I need to shift the color in an image, e.g. from gray to green. But only the parts that are not white and/or black...

For UIKit I had a handy extension:

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

is there any way to generate the same functionality with the tint options in SwiftUI?

".colorMultiply" colors white as well.

".saturation(0.5)" directly generates a grayscale image.


Solution

  • I was looking for the wrong keyword.

    The actually way to do this in SwiftUI is hueRotation! It only works with coloured images and not with grayscale images though.

    See example below:

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