Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill shape with Gradient in SwiftUI

Tags:

ios

swift

swiftui

how can i pass LinearGradient to a shape (for example Rectangle) just in SwiftUI?

Rectangle().frame(width: UIScreen.main.bounds.width, height: 200)
like image 448
Sajad Beheshti Avatar asked Jun 07 '19 05:06

Sajad Beheshti


2 Answers

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)
}
like image 83
M Reza Avatar answered Oct 11 '22 04:10

M Reza


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
like image 38
Jonas Deichelmann Avatar answered Oct 11 '22 04:10

Jonas Deichelmann