I would like to create a gradient layer with four given colours. I have a sketch file for the gradients. I have the coordinates for the colour stops. I calculated the normalised coordinates for the start and the end point for the CAGradientLayer. I also calculated the location where the colours change each other. Still the layer does not match with the sketch image. Can you help me what could be wrong? Usage of the exported image is not an option because the layer has to change with animation to other gradient locations.
let imageWidth: CGFloat = 375.0
let imageHeihgt: CGFloat = 293.0
class ViewController: UIViewController {
let homeColors: [UIColor] = [UIColor(red: 62/255, green: 131/255, blue: 255/255, alpha: 1.0),
UIColor(red: 99/255, green: 22/255, blue: 203/255, alpha: 1.0),
UIColor(red: 122/255, green: 5/255, blue: 239/255, alpha: 1.0),
UIColor(red: 122/255, green: 5/255, blue: 240/255, alpha: 1.0)]
let startPoint: CGPoint = CGPoint(x: -0.225/imageWidth*UIScreen.main.bounds.width, y: -0.582*imageHeihgt/UIScreen.main.bounds.height)
let endPoint: CGPoint = CGPoint(x: 1.088/imageWidth*UIScreen.main.bounds.width, y: 1.01*imageHeihgt/UIScreen.main.bounds.height)
let locations: [NSNumber] = [0.0, 0.734, 0.962, 1.0]
var subview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
subview = UIView(frame: CGRect(x: 0, y: 20, width: imageWidth, height: imageHeihgt))
view.addSubview(subview)
view.sendSubview(toBack: subview)
addGradientLayer()
}
func addGradientLayer() {
let gradient = CAGradientLayer()
gradient.frame = subview.bounds
gradient.colors = homeColors.map { $0.cgColor }
gradient.startPoint = startPoint
gradient.endPoint = endPoint
gradient.locations = locations
subview.layer.insertSublayer(gradient, at: 0)
}
}
I have attached some screenshots to make the difference clear. It is not a big difference but still.