我找不到任何有关如何在前景上为我使用SwiftUI的图像进行线性渐变的相关文档。
我试着这样做:
Image("IconLoseWeight")
.frame(width: 30.0, height: 30.0)
.padding(.leading, 17)
.foregroundColor(LinearGradient(gradient: Gradient(colors: [.white, .black]), startPoint: .top, endPoint: .bottom))
实际上,上面显示的代码没有显示任何错误,但它用顶级堆栈中毫无意义的警告破坏了代码(我认为这是Xcode或SwiftUI的错误)。如果删除foreground
修饰符,代码将完美运行。
4条答案
按热度按时间qhhrdooz1#
这是因为前景颜色需要
Color
,但LinearGradient
是符合协议ShapeStyle
和View
的struct
。如果我理解正确的话,你想用渐变来填充图像的不透明区域?
结果看起来是这样的:
rn0zuynd2#
这里的任务是在图像上显示渐变。为了在另一个视图上显示一个视图,SwiftUI提供了
ZStack
视图,因此,代码可以具有下一个结构:此外,为了确保我们使用的图像的大小正确调整到指定的帧
resizable
,应该使用正确的contentMode
应用修改器:毕竟,我们需要将
frame
和填充参数应用到ZStack
,以便渐变具有与图像相同的大小。结果将如下所示:
请注意,我们使用从
.clear
到.black
的渐变,因为我们需要一个透明的渐变来使图像可见。gfttwv5a3#
同意@RyuX51的答案,它工作得很好。但我的图像的大小和对齐方式发生了一些变化。因为未设置
LinearGradient
的frame
。所以在这里我想出了一个解决方案,只需将渐变应用到
Image
,rm5edbpk4#
要做到这一点,最新的SwiftUI版本的最佳方法是使用
.foregroundStyle()
视图修饰符。我不确定这种方法是什么时候出现的,但这段代码已经在Xcode14和iOS 16上进行了测试。示例代码如下: