如何在 SwiftUI 中设置图像色调?

Nic*_*vit 29 swiftui

我正在尝试在 SwiftUIImage类中设置图像色调

对于 UIKit,我可以使用设置图像色调

let image = UIImage(systemName: "cart")!.withTintColor(.blue)
Run Code Online (Sandbox Code Playgroud)

但我在 swiftui 文档中找不到这样的设置

atu*_*n23 47

swiftUI套装tint使用:

Image("ImageName")
  .foregroundColor(.red)
Run Code Online (Sandbox Code Playgroud)

根据源图像,您可能还需要额外的渲染模式修改器:

Image("ImageName")
  .renderingMode(.template)
  .colorMultiply(.red)
// or
Image("ImageName")
  .colorMultiply(.blue)
Run Code Online (Sandbox Code Playgroud)

您可以阅读此主题

  • 根据源图像,您可能还需要额外的渲染模式修饰符:`Image("ImageName").renderingMode(.template).colorMultiply(.red)` (3认同)
  • 此解决方案的问题在于,根据您处于浅色模式还是深色模式,模板图像可能会以黑色开始,而 .colorMultiply 将没有。颜色乘法根据图像的原始颜色给出不同的结果。 (2认同)

Mon*_*ona 38

这对我有用,

Image("ImageName")
   .renderingMode(.template)
   .foregroundColor(.white)
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为它在浅色和深色模式下都有效。 (2认同)

ARG*_*Geo 12

混合模式

对于着色,您可以使用.blendMode修改器将图像与其他图像或颜色合成。Xcode 14.0+ 中有 20 多种类似 Photoshop 的混合模式。最适合 SwiftUI 着色的混合模式是:

  • 。柔光
  • 。覆盖
  • 。亮度
  • 。屏幕

在此输入图像描述

如果更改混合颜色的亮度和饱和度,您将得到与此处看到的不同的结果。

在此输入图像描述

这是代码:

struct ContentView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .fill(Gradient(colors: [.red, .yellow]))
                .ignoresSafeArea()
            Image("XcodeIcon")
                .resizable()
                .scaledToFit()
                .blendMode(.softLight)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Rab*_*med 8

SwiftUI 4.x:

方法一:

Image("your_image_name")
    .resizable()
    .renderingMode(.template)
    .foregroundColor(.white)
Run Code Online (Sandbox Code Playgroud)

方法2:

Image("your_image_name")
  .resizable()
  .renderingMode(.template)
  .colorMultiply(.red) 
Run Code Online (Sandbox Code Playgroud)