简体   繁体   English

从黑色到完全透明的快速渐变

[英]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.我正在尝试使用 swift 应用 CAGradientLayer,我希望它从黑色淡入透明。

I thought putting any color with an alpha: 0 would render the same "transparent" color.我认为用alpha: 0放置任何颜色都会呈现相同的“透明”颜色。 It is not the case.事实并非如此。 White with alpha: 0 is still a bit white, red with alpha: 0 is still a bit red...带有alpha: 0白色仍然有点白,带有alpha: 0的红色仍然有点红......

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:编辑 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.它在我的情况下有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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