I am trying to set an image tint in SwiftUI Image class
For UIKit, I can set image tint using
let image = UIImage(systemName: "cart")!.withTintColor(.blue)
but I cant find such settings in swiftui docs
I am trying to set an image tint in SwiftUI Image class
For UIKit, I can set image tint using
let image = UIImage(systemName: "cart")!.withTintColor(.blue)
but I cant find such settings in swiftui docs
On new swiftUI for set tint use:
Image("ImageName")
.foregroundColor(.red)
Depending on the source image you may also need an additional rendering mode modifier:
Image("ImageName")
.renderingMode(.template)
.colorMultiply(.red)
// or
Image("ImageName")
.colorMultiply(.blue)
And you can read this topic.
This worked for me,
Image("ImageName")
.renderingMode(.template)
.foregroundColor(.white)
The above answer is probably the best one although this would work too:
let uiImage = UIImage(systemName: "cart")!.withTintColor(.blue)
let image = Image(uiImage: uiImage)
Then you can use the constant named image with SwiftUI.
This recipe shows how to tint SwiftUI images in two ways - by setting the template tint or color multiply. The result looks like this:
Let's start by saying that foreground color has no effect here. With that out of the way, the recipe depends on what you want to do with the image since I've seen tint being used in more than one context:
For photos and logos with multi-color images, use color multiply Half of the time, "tinting an image" means the following:
This is achieved by using the color multiple modifier on the Image:
Image("logo_small")
.colorMultiply(.green)
For monochrome images, use rendering mode
If you have a monochrome image or one where all that matters is the outline, use rendering mode with the template, then apply `foreground color. This will set the color to all non-transparent pixels in the image:
Image("swift")
.renderingMode(.template)
.foregroundColor(.blue)
With the following effect:
Using color multiple with monochrome images usually leads to undesired results, like the entire image is black.
Done ;)
For tinting, you can use the .blendMode modifier to composite your image with another image or with color. There are 20+ Photoshop-like blending modes in Xcode 14.0+. The most appropriate SwiftUI's blending modes for tinting are:
You'll get different results than you see here if you change the brightness and saturation of the blending color.
Here's the code:
struct ContentView: View {
var body: some View {
ZStack {
Rectangle()
.fill(Gradient(colors: [.red, .yellow]))
.ignoresSafeArea()
Image("XcodeIcon")
.resizable()
.scaledToFit()
.blendMode(.softLight)
}
}
}