CAGradientLayer in SwiftUI

571 Views Asked by At

I'm converting my project to SwiftUI and I use a background with gradient. I can't figure out how to convert the below to a SwiftUI view:

let layer = CAGradientLayer()
layer.colors = [
  UIColor(red: 0.165, green: 0.224, blue: 0.314, alpha: 1).cgColor,
  UIColor(red: 0.112, green: 0.17, blue: 0.26, alpha: 1).cgColor]

layer.locations = [0.45, 1]
layer.startPoint = CGPoint(x: 0.25, y: 0.5)
layer.endPoint = CGPoint(x: 0.75, y: 0.5)
layer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(a: 0, b: 0.46, c: -0.46, d: 0, tx: 0.73, ty: 0.68))
layer.bounds = view.bounds.insetBy(dx: -0.5*view.bounds.size.width, dy: -0.5*view.bounds.size.height)
layer.position = view.center
view.layer.addSublayer(layer)

I tried the below, but the results are not the same:

LinearGradient(gradient: Gradient(colors: [Color("BackgroundNEWTop"), Color("BackgroundNEWBottom")]), startPoint: .top, endPoint: .bottom))
1

There are 1 best solutions below

2
Steven-Carrot On BEST ANSWER

After I tested your UIKit code, this is the closest one I replicated in SwiftUI. I included the result image here, but you should try this code yourself first because the online image may look slightly different.

Sample Code and Image are below:

enter image description here

struct SampleView: View {
  let color1 = Color.init(red: 0.112, green: 0.17, blue: 0.26)
  let color2 = Color.init(red: 0.165, green: 0.224, blue: 0.314)
  var body: some View {
    ZStack {
        LinearGradient(colors: [color1, color2],
                       startPoint: UnitPoint(x: 0.75, y: 0.5),
                       endPoint: UnitPoint(x: 0.25, y: 0.5))
    }
  }
}