Search code examples
animationstoryboardcalayerswift5xcode11

What is CALayer and CAGradientLayer?


Can anyone please explain what is CALayer And CAGradientLayer in simple language and how can I achieve the following gradient programmatically.

I want to achieve this gradient colour programmatically:

gradient


Solution

  • I suggest you do some searching for CALayer and CAGradientLayer and read up on what they are, and how to use them.

    However, for a very simple example...

    A CAGradientLayer uses an array of colors (CGColor type), combined with an array of locations (percentages where the colors should change), and starting and ending points.

    So, to get your color gradient, you want an array of colors:

    [.purple, .blue, .green, .yellow, .red]
    

    an array of locations:

    [0.0, 0.2, 0.4, 0.6, 1.0]
    

    and you want to start at the Top and end at the Bottom:

    gradLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
    gradLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    

    Here's a simple example:

    class ViewController: UIViewController {
        
        let gradLayer = CAGradientLayer()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let myColors: [UIColor] = [.purple, .blue, .green, .yellow, .red]
            
            // assign the colors (we're using map to convert UIColors to CGColors)
            gradLayer.colors = myColors.map({$0.cgColor})
            
            // locations can be considered Percentages
            // so, 0.2 is 20%, 0.4 is 40%, etc
            gradLayer.locations = [0.0, 0.2, 0.4, 0.6, 1.0]
            
            // start at the top
            gradLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
            
            // end at the bottom
            gradLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    
            view.layer.addSublayer(gradLayer)
            
        }
        
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            // layers do not auto-size, so update the frame
            gradLayer.frame = view.bounds
        }
    
    }
    

    Result:

    enter image description here

    Play with the locations and colors to see the differences.