如何在 SwiftUI 中使用渐变填充形状

How to fill shape with Gradient in SwiftUI

如何在 SwiftUI 中将 LinearGradient 传递给形状(例如矩形)只是

Rectangle().frame(width: UIScreen.main.bounds.width, height: 200)

这应该有效:

static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255)
static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 120.0 / 255)

var body: some View {
  Rectangle()
    .fill(LinearGradient(
      gradient: .init(colors: [Self.gradientStart, Self.gradientEnd]),
      startPoint: .init(x: 0.5, y: 0),
      endPoint: .init(x: 0.5, y: 0.6)
    ))
    .frame(width: 300, height: 200)
}

从 beta 6 开始,您必须先将 forgroundColor 设置为清除。

Rectangle()
    .foregroundColor(.clear)
    .background(LinearGradient(gradient:  Gradient(colors: [Color("gradient1"), Color("gradient2")]), startPoint: .top, endPoint: .bottom))
Rectangle().frame(width: UIScreen.main.bounds.width, height: 200) // You original code

.overlay(
    LinearGradient(gradient: Gradient(colors: [.red, .purple]), startPoint: .top, endPoint: .bottom))
)

注意:

When you apply an overlay to a view, the original view continues to provide the layout characteristics for the resulting view.

SwiftUI

这是一个可能的解决方案。

struct TestSwiftUIView: View {
    let uiscreen = UIScreen.main.bounds

    var body: some View {
        Rectangle()
        .fill(
            LinearGradient(gradient: Gradient(colors: [Color.clear, Color.black]),
                           startPoint: .top,
                           endPoint: .bottom))
        .frame(width: self.uiscreen.width,
               height: self.uiscreen.height,
               alignment: .center)
    }
}

此代码片段将生成如下屏幕:

startPointendPointUnitPoint。对于 UnitPoints,您有以下选项:

.zero

.center

.leading

.trailing

.top

.bottom

.topLeading

.topTrailing

.bottomLeading

.bottomTrailing