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

时间:2019-06-07 05:45:12

标签: swift swiftui

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

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

4 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分:2)

Rectangle().frame(width: UIScreen.main.bounds.width, height: 200) // You original code

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

请注意:

将叠加层应用于视图时,原始视图将继续为结果视图提供布局特征。

答案 2 :(得分:1)

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)
    }
}

此代码段将产生如下屏幕:

Showing a screen with a gradient from white to black

startPointendPointUnitPoint。对于UnitPoint,您可以使用以下选项:

.zero

.center

.leading

.trailing

.top

.bottom

.topLeading

.topTrailing

.bottomLeading

.bottomTrailing

答案 3 :(得分:0)

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

Rectangle()
    .foregroundColor(.clear)
    .background(LinearGradient(gradient:  Gradient(colors: [Color("gradient1"), Color("gradient2")]), startPoint: .top, endPoint: .bottom))