10

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

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

4 回答 4

22

这应该有效:

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)
}
于 2019-06-07T06:01:18.387 回答
4

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
于 2020-04-16T12:01:24.980 回答
2
Rectangle().frame(width: UIScreen.main.bounds.width, height: 200) // You original code

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

注意:

当您将覆盖应用到视图时,原始视图会继续为结果视图提供布局特征。

于 2020-02-03T14:34:07.017 回答
1

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

Rectangle()
    .foregroundColor(.clear)
    .background(LinearGradient(gradient:  Gradient(colors: [Color("gradient1"), Color("gradient2")]), startPoint: .top, endPoint: .bottom))
于 2019-08-23T19:23:57.383 回答