【问题标题】:How can I set an image tint in SwiftUI?如何在 SwiftUI 中设置图像色调?
【发布时间】:2020-07-23 22:07:36
【问题描述】:

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

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

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

但我在 swiftui 文档中找不到此类设置

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    在新的swiftUI 上设置tint 使用:

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

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

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

    你可以阅读这个topic

    【讨论】:

    • 根据源图像,您可能还需要一个额外的渲染模式修改器:Image("ImageName").renderingMode(.template).colorMultiply(.red)
    • 这个解决方案的问题在于,根据您是处于浅色模式还是深色模式,模板图像可能以黑色开始,而 .colorMultiply 则不会。颜色乘法根据图像的原始颜色给出不同的结果。
    【解决方案2】:

    这对我有用,

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

    【讨论】:

    • 这应该是公认的答案,因为它可以在明暗模式下工作。
    • 这是唯一对我有用的答案
    【解决方案3】:

    上述答案可能是最好的答案,尽管这也可以:

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

    然后你可以在 SwiftUI 中使用名为 image 的常量。

    【讨论】:

    • 您可能需要全局声明uiImage。我就是这样做的,它对我有用。
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2019-12-21
    • 2023-04-01
    相关资源
    最近更新 更多