3

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

1 Answer 1

1

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))
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it seems to go left to right rather than top to bottom though.
I got a bit closer with this: LinearGradient( gradient: Gradient(stops: [ .init(color: Color.init(red: 0.112, green: 0.17, blue: 0.26), location: 0.45), .init(color: Color.init(red: 0.165, green: 0.224, blue: 0.314), location: 1)]), startPoint: UnitPoint(x: 0.5, y: 1.14), endPoint: UnitPoint(x: 0.5, y: 0.683)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.