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

标签 ios swift calayer cagradientlayer

我正在尝试使用 swift 应用 CAGradientLayer,我希望它从黑色逐渐变为透明。

我认为用 alpha: 0 放置任何颜色都会呈现相同的“透明”颜色。事实并非如此。 alpha: 0 的白色还是有点白,alpha: 0 的红色还是有点红...

我不想要任何色调,只想要透明的。黑色不那么黑,以至于没有颜色,例如您可以完全看到它下面的 View 。

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]

如果我将图层应用到灰色图片上,很容易看出它不是透明的而是白色的:

enter image description here

编辑 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)

输出:

enter image description here

最佳答案

你可以试试这个:

    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)

它在我的案例中起作用。

关于ios - 从黑色到完全透明的快速渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109930/

相关文章:

ios - 从 UIWebView 进行 PDF 分页

iphone - UIButton + 斜体字体 = 剪裁

iOS - TableView 错误

ios - 带有 UIRectCornerBottomLeft/Right 的 CAShapeLayer 使我的 View 消失

cocoa - 从 MacOS 应用程序将文件写入 iOS 设备

swift - 是否可以将用户位置从 iOS 应用程序发送到网络服务器?

swift - 如何从具有同名嵌套类型的类中引用全局类型?

ios - 异步函数不更新变量

objective-c - 为什么我的 CATextLayer 不响应contentsGravity 属性?

ios - 如何禁用 CALayer 隐式动画?