Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift gradient from black to fully transparent

I am trying to apply a CAGradientLayer using swift, and I would like it to fade from black to transparent.

I thought putting any color with an alpha: 0 would render the same "transparent" color. It is not the case. White with alpha: 0 is still a bit white, red with alpha: 0 is still a bit red...

I don't want any tint, just transparent. The black being less black to the point theres no color and you can fully see the view under it for example.

gradientLayer.colors = [UIColor(hex: 0x000000, alpha: 0.4).cgColor,
                        UIColor(hex: 0x6D6D6D, alpha: 0.3).cgColor,
                        UIColor.white.withAlphaComponent(0.0).cgColor]
gradientLayer.locations = [0.0, 0.3, 1.0]

If I apply the layer over a gray picture, it's easy to see that its not transparent but white:

enter image description here

EDIT 1:

gradientLayer.frame = self.gradientView.bounds
gradientLayer.masksToBounds = true
gradientLayer.colors = [UIColor.black.withAlphaComponent(1.0).cgColor, UIColor.black.withAlphaComponent(0.0).cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
self.gradientView.layer.addSublayer(gradientLayer)

Output :

enter image description here

like image 990
Scaraux Avatar asked May 01 '18 00:05

Scaraux


1 Answers

You can try this:

    gradientLayer.colors = [UIColor.black.withAlphaComponent(1.0).cgColor,
                            UIColor.black.withAlphaComponent(0.0).cgColor]
    //gradientLayer.locations = [0.0, 1.0]
    gradientLayer.frame = myView.bound
    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
    myView.layer.insertSublayer(gradientLayer, at: 0)

It worked in my case.

like image 182
Chanchal Chauhan Avatar answered Nov 18 '22 12:11

Chanchal Chauhan