Linear Gradient in Swift

 

Linear Gradient
  Linear Gradient Color

With CoreAnimation and CAGradientLayer, iOS makes it easy to create custom gradients of any style. It is possible to create linear, conic and radial gradients, and to customize as you want its colors and orientation. It even supports animating gradient changes for smooth and colourful apps.

CAGradientLayer is a subclass of CALayer, and has been specially designed to easily and quickly make gradient effects. With literally five lines of code, you can generate a new gradient and add it to your view layers.

1. Linear Gradient

Creating a layer with gradient colors is quite simple. For the most basic gradient, it only requires the colors you want to use, and then you can optionally adjust color location. Once you’ve created your gradient, add it simply to your view layer by calling the addSublayer function.

//
//  ViewController.swift
//  CAGradientLayerApp
//
//  Created by JOYNAL ABEDIN on 8/9/22.
//

import UIKit

class ViewController: UIViewController {
    
    lazy var gradient: CAGradientLayer = {
        let gradient = CAGradientLayer()
        gradient.type = .axial
        gradient.colors = [
            UIColor.red.cgColor,
            UIColor.purple.cgColor,
            UIColor.cyan.cgColor
        ]
        //top-left corner/// startPoint = CGPoint(x: 0, y: 0), endPoint = CGPoint(x: 1, y: 1)
        //top-right corner/// startPoint = CGPoint(x: 1, y: 0), endPoint = CGPoint(x: 0, y: 1)
        //bottom-left corner/// startPoint = CGPoint(x: 0, y: 1), endPoint = CGPoint(x: 1, y: 0)
        //bottom-right corner/// startPoint = CGPoint(x: 1, y: 1), endPoint = CGPoint(x: 0, y: 0)
        
        gradient.locations = [0, 0.5, 1]
        gradient.startPoint = CGPoint(x: 1, y: 1)
        gradient.endPoint = CGPoint(x: 0, y: 0)
        return gradient
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        gradient.frame = view.bounds
        view.layer.addSublayer(gradient)
        
    }

}

The attribute type is optional for this style of gradient, as linear (or axial) gradient is the default type. Also, the location of colors are useful only if you need to adjust how much space you want for each color. Otherwise, it is also optional. If you don’t set this property, each color of the gradient will just show proportionally on the layer.

1,360 thoughts on “Linear Gradient in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *