简体   繁体   中英

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:

在此处输入图片说明

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 :

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM