TransWikia.com

Adding horizontal gradient to borderline

Stack Overflow Asked by Tarvo Mäesepp on January 7, 2021

I created simple borderline into my view. However I am struggling giving horizontal gradient background color to it. How should I do it?

I tried like this but it just sets the color to white:

    let border = CAGradientLayer()
    border.frame = CGRect(x: 0, y: self.mainView.frame.height - 2, width: self.mainView.frame.width, height: 2)
    border.backgroundColor = UIColor.gray.cgColor
    let color1 = UIColor.black.withAlphaComponent(0.1).cgColor as CGColor
    let color2 = UIColor.white.withAlphaComponent(0.9).cgColor as CGColor
    border.locations = [0.60, 1.0]// Are these right coordinates?
    border.colors = [color2, color1]

One Answer

I got it working like this:

let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(x: 0, y: self.mainView.frame.height - 2, width: self.mainView.frame.width, height: 2)
gradientLayer.colors =  [UIColor.green,UIColor.blue ].map{$0.cgColor}
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

Instead of using CALayer() I had to use CAGradientLayer()

Correct answer by Tarvo Mäesepp on January 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP