How to fill shape with Gradient in SwiftUI

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

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

Note that:

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


This should work:

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

SwiftUI

Here is a possible solution.

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

This code snippet will produce a screen like that:

Showing a screen with a gradient from white to black

The startPoint and the endPoint are UnitPoint. For UnitPoints you have the following options:

.zero

.center

.leading

.trailing

.top

.bottom

.topLeading

.topTrailing

.bottomLeading

.bottomTrailing

As of beta 6, you must set the forgroundColor to clear first.

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

Tags:

Ios

Swift

Swiftui