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

72

我正在尝试在SwiftUI Image类中设置图像色调。

对于UIKit,我可以使用以下方法设置图像色调:

let image = UIImage(systemName: "cart")!.withTintColor(.blue)

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

6个回答

112

在新的 SwiftUI 中设置 tint 的方法如下:

Image("ImageName")
  .foregroundColor(.red)

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

Image("ImageName")
  .renderingMode(.template)
  .colorMultiply(.red)
// or
Image("ImageName")
  .colorMultiply(.blue)

你可以阅读这个主题


3
根据源图像的不同,您可能需要使用额外的渲染模式修饰符:Image("ImageName").renderingMode(.template).colorMultiply(.red) - dead_can_dance
2
这个解决方案的问题在于,根据你是处于浅色模式还是深色模式,模板图像可能会以黑色开始,而.colorMultiply将没有作用。.colorMultiply根据图像的原始颜色给出不同的结果。 - bitwit
1
由于某种原因,如果我使用renderingMode + colorMultiply,一些颜色会表现得很奇怪(例如,白色会变成蓝色)。所以我只是用foregroundColor替换了colorMultiply。最终结果:Image("ImageName").renderingMode(.template).foregroundColor(.red) - Caio Ambrosio

71

这对我有用,

Image("ImageName")
   .renderingMode(.template)
   .foregroundColor(.white)

2
这应该是被接受的答案,因为它可以在明亮和暗黑模式下工作。 - bitwit
1
这是唯一对我有效的答案。 - rmp251
这是唯一对我有效的方法。 - Daniel Wijono

15
此教程展示了两种方法如何为SwiftUI图像设置模板着色或颜色倍增。结果看起来像这样:

enter image description here

让我们先说一下前景颜色在这里没有影响。既然这个问题解决了,配方取决于您想对图像做什么,因为我看到过在不止一个上下文中使用色调:
对于具有多色图像的照片和标志,请使用颜色相乘 一半的时间,“给图像着色”意味着以下内容:

enter image description here

这可以通过在Image上使用color multiple修饰符来实现:
Image("logo_small")
  .colorMultiply(.green)

对于单色图像,请使用渲染模式

如果您有一张单色图像或者只有轮廓很重要的图像,请使用 template 的渲染模式,然后应用前景色。这将把颜色设置为图像中所有非透明像素的颜色:

Image("swift")
  .renderingMode(.template)
  .foregroundColor(.blue)

具有以下效果:

enter image description here

使用 color multiple 命令处理单色图像通常会导致不良结果,例如整个图像变成黑色。

11

混合模式

为了进行着色,您可以使用 .blendMode 修改器将您的图像与另一个图像或颜色进行组合。在 Xcode 14.0+ 中有 20 多种类似于 Photoshop 的混合模式可用。 SwiftUI 最适合着色的混合模式是:

  • .softLight
  • .overlay
  • .luminosity
  • .screen

进入图片描述

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

进入图片描述

以下是代码:

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

8

SwiftUI 4.x:

方案1:

Image("your_image_name")
    .resizable()
    .renderingMode(.template)
    .foregroundColor(.white)

方法二:

Image("your_image_name")
  .resizable()
  .renderingMode(.template)
  .colorMultiply(.red) 

3
上面的答案可能是最好的,但这个也可以:
let uiImage = UIImage(systemName: "cart")!.withTintColor(.blue)
let image = Image(uiImage: uiImage)

那么你就可以使用名为 image 的常量与SwiftUI一起使用。


你可能需要在全局范围内声明 uiImage。我就是这样做的,这对我有用。 - Todd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接