当我尝试使用渐变创建圆角矩形时,我目前遇到了“粗糙”边缘的问题。
在此渐变中,您可以看到拐角处变得特别暗,我不知道如何解决这个问题。
我猜这源于使用扩展来创建渐变,以便我可以将它用作前景色而不是背景,但我不确定我会用什么来解决这个问题。>
var body: some View {
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 20)
.gradientForeground(colors: [Color("MainColor1"), Color("MainColor2")])
.frame(width: geometry.size.width * 0.9, height: 100, alignment: .center)
.padding(.leading, geometry.size.width * 0.05)
}
}
}
extension View {
public func gradientForeground(colors: [Color]) -> some View {
self.overlay(LinearGradient(gradient: .init(colors: colors),
startPoint: .topLeading,
endPoint: .bottomTrailing))
.mask(self)
}
}
答案 0 :(得分:1)
由于您使用了 RoundedRectangle
,因此您正在处理 Shape,正确且正确的着色方式是 fill
,您的问题与 View< 无关/strong> 进行扩展,但它是关于形状。
extension Shape {
public func gradientForeground(colors: [Color]) -> some View {
self.fill(LinearGradient(gradient: .init(colors: colors), startPoint: .topLeading, endPoint: .bottomTrailing))
}
}
用例:
struct ContentView: View {
var body: some View {
RoundedRectangle(cornerRadius: 50)
.gradientForeground(colors: [Color.red, Color.yellow])
.frame(width: 300, height: 300, alignment: Alignment.center)
}
}