1

How do I apply a linear gradient with a custom class that I made on a shape? For some reason it is not working for me. The foregroundColor is not working for me.

  RoundedRectangle(cornerRadius: 30)
                            .frame(width: geometry.size.width * 1.01, height:geometry.size.height * 0.23)
                            .rotationEffect(.degrees(12), anchor: .center)
                            .foregroundColor(LinearGradient (gradient: Gradient(colors:[Color(ColorsSaved.gitLabDark),Color(ColorsSaved.gitLabLight)]),startPoint: .leading,endPoint: .trailing))

I created my CustomClass in a Swift file. Please see code below for that.

import Foundation
import UIKit

struct ColorsSaved {
static let gitLabDark = UIColor( red: 0.12, green: 0.08, blue: 0.22, alpha: 1.0)
static let gitLabLight = UIColor( red: 0.26, green: 0.2, blue: 0.44, alpha: 1.0)
static let neonGreen =  UIColor(red: 0.497, green: 0.738, blue: 0.35, alpha: 1)
static let darkGreenTorquise = UIColor(red: 0.242, green: 0.683, blue: 0.577, alpha: 1)
static let brightOrange =   UIColor(red: 0.917, green: 0.469, blue: 0.218, alpha: 1)
bain
  • 335
  • 1
  • 6
  • 17

2 Answers2

1

If I correctly understood your intention, I would go with the following approach.

Result demo: SwiftUI shape with gradient

Code:

GeometryReader { geometry in
    LinearGradient(gradient: 
          Gradient(colors:
             [Color(ColorsSaved.gitLabDark), Color(ColorsSaved.gitLabLight)]), 
          startPoint: .leading, endPoint: .trailing)
    .frame(width: geometry.size.width * 1.01, height:geometry.size.height * 0.23)
    .mask(RoundedRectangle(cornerRadius: 30))
    .rotationEffect(.degrees(12), anchor: .center)
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
-1

Gradients in SwiftUI are supposed to be added with the help of ZStack. As you haven't added much code in your question I made my assumptions. Try this in your custom view:

struct WelcomeView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.pink, .purple]), startPoint: .leading, endPoint: .trailing)
            // here goes your other view component
            Text("Welcome, John")
        }
    }
}
nayem
  • 7,285
  • 1
  • 33
  • 51