SwiftUI - 如何在图像上添加前景线性渐变

SwiftUI - How to add foreground linear gradient on image

我找不到任何关于如何在 前景 上为我使用 SwiftUI 的图像做线性渐变的相关文档。

我试过这样做:

Image("IconLoseWeight")
  .frame(width: 30.0, height: 30.0)
  .padding(.leading, 17)
  .foregroundColor(LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .top, endPoint: .bottom))

实际上,上面显示的代码没有显示任何错误,但它用在顶级 Stacks 中没有意义的警告破坏了代码(我认为这是 Xcode 或 SwiftUI 的错误) .如果我删除 foreground 修饰符,代码将完美运行。

这里的任务是在图像上显示渐变。为了在另一个视图上显示一个视图,SwiftUI 提供了 ZStack 视图,因此,代码可以具有下一个结构:

ZStack {
    <Image>
    <Rectangle with gradient>
}

此外,为了确保我们使用的图像正确调整到指定的帧大小 resizable 修改器应该应用正确的 contentMode:

Image("IconLoseWeight")
    .resizable()                     // Make it resizable
    .aspectRatio(contentMode: .fit)  // Specifying the resizing mode so that image scaled correctly

毕竟,我们需要对 ZStack 应用 frame 和 padding 参数,以便渐变具有与图像相同的大小。

结果应该是这样的:

ZStack {
    Image("IconLoseWeight")
        .resizable()                    // Making the image resizable to the container size
        .aspectRatio(contentMode: .fit) // Setting up resizing mode so that the image scaled correctly

    Rectangle()                         // Shapes are resizable by default
        .foregroundColor(.clear)        // Making rectangle transparent
        .background(LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .top, endPoint: .bottom), cornerRadius: 0)   
                                        // Specifying gradient (note that one color is .clear)
}
.frame(width: 30, height: 30)           // Applying frame
.padding(.leading, 17)                  // Applying padding

请注意,我们使用从 .clear.black 的渐变,因为我们需要透明渐变以使图像可见。

那是因为 foregroundColor 想要一个 Color,但是 LinearGradient 是一个 struct,它符合协议 ShapeStyleView

如果我没理解错的话,您想用渐变填充图像的不透明区域吗?

ZStack {
  Color.white // For the background. If you don't need a background, you don't need the ZStack.
  LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .top, endPoint: .bottom)
    .mask(Image("AssetWithTransparency")
      .resizable()
      .padding()
      .aspectRatio(contentMode: .fit))
  }.cornerRadius(15)

结果如下所示:

同意@RyuX51 的回答,效果很好。但是我的图像的大小和对齐方式发生了一些变化。因为 LinearGradientframe 没有设置。
所以在这里我想到了将渐变应用于 Image

的解决方案
VStack{
    Spacer()
    Button(action: {
        print("Add Photos")
    }, label: {

        LinearGradient(gradient: Gradient(colors: [.green, .blue]), startPoint: .top, endPoint: .bottom)
            .mask(Image(systemName: "plus.circle.fill")
            .resizable()
            .aspectRatio(contentMode: .fit)
        ).frame(width: 70, height: 70, alignment: .center)
    })
}