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

Rod*_*ata 3 macos xcode ios swift swiftui

我找不到任何有关如何使用SwiftUI 在前景上对图像进行线性渐变的相关文档。

我试图这样做:

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

实际上,上面显示的代码不会显示任何错误,但是会使用在顶级堆栈中没有意义的警告来打乱代码(我认为这是Xcode或SwiftUI的错误)。如果删除foreground修饰符,则代码可以完美运行。

Den*_*nis 17

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

ZStack {
    <Image>
    <Rectangle with gradient>
}
Run Code Online (Sandbox Code Playgroud)

此外,为了确保我们使用的图像被正确调整为指定的帧resizable修饰符,应该使用正确的contentMode

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

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

结果看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

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


小智 9

从最新的 SwiftUI 版本开始,执行此操作的最佳方法是使用.foregroundStyle()视图修饰符。我不确定这种方法何时可用,但此代码已使用 Xcode 14 和 iOS 16 进行了测试。

示例代码如下:

let gradient = Gradient(colors: [.purple, .cyan, .orange])

var body: some View {
    Image(systemName: "figure.strengthtraining.traditional")
        .font(.title)
        .foregroundStyle(.linearGradient(gradient, startPoint: .top, endPoint: .bottom))
}
Run Code Online (Sandbox Code Playgroud)


Ryu*_*X51 5

这是因为frontendColor需要a Color,但是LinearGradienta struct符合协议ShapeStyleand View

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

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)
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样:

在此处输入图片说明