Search code examples
swiftbackground-coloruicolorcagradientlayer

Shade and mix two color with percent , horizontally and vertically in swift


I wanted to Mix two colors shaded and divided equally.

enter image description here

(Ignore the buttons inside of it) Also, I want to apply this functionality somewhere horizontally and somewhere vertically.

Thank you.


Solution

  • The way you are looking for is CAGradientLayer.

    For Vertical

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.gradientView.bounds
    gradientLayer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor] //Add different color here
    self.gradientView.layer.addSublayer(gradientLayer) //Add Layer in your View
    

    For Horizontal simply set startPoint and endPoint with gradientLayer.

    gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)