在顶部淡化UIView颜色

时间:2016-10-04 12:07:36

标签: ios iphone swift cocoa-touch uiview

我有一个基本的UIView我是通过Interface Builder(XIB)创建的。

我希望得到这种效果(在图像中:我在图像上方的视图):

Image 如何让UIView的背景颜色在顶部淡出?

谢谢!

1 个答案:

答案 0 :(得分:0)

你的意思是添加" gradient"效果你的UIView。为此,您需要添加CAGradientLayer,您可以创建与此类似的自定义UIView

class CustomView: UIView {
    private let gradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        super.awakeFromNib()

        addGradient()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // update gradient
        gradientLayer.frame = self.bounds
    }

    private func addGradient() {
        // declaring colors for your gradient:
        // top color is clear
        let topColor = UIColor.clear.cgColor
        // bottom color is black
        let bottomColor = UIColor.black.cgColor

        gradientLayer.frame = self.frame

        // add colors to the gradientLayer:
        gradientLayer.colors = [topColor, bottomColor]

        // change the startPoint and endPoint to make it appears like it should...
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)

        // add the gradient to your view (which in my case is gradientView)
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}