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

Saj*_*hti 2 swift swiftui

如何在SwiftUI中将LinearGradient传递给形状(例如Rectangle)?

Rectangle().frame(width: UIScreen.main.bounds.width, height: 200)
Run Code Online (Sandbox Code Playgroud)

Jon*_*ann 7

斯威夫特用户界面

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

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

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

显示从白到黑渐变的屏幕

startPoint是。endPointUnitPoint对于 UnitPoints,您有以下选项:

.zero

.center

.leading

.trailing

.top

.bottom

.topLeading

.topTrailing

.bottomLeading

.bottomTrailing
Run Code Online (Sandbox Code Playgroud)


Mo *_*ani 5

这应该工作:

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