iOS White to Transparent Gradient Layer is Gray

前端 未结 7 1210
清歌不尽
清歌不尽 2021-02-01 11:53

I have a CAGradientLayer inserted to the bottom of this small detail view that pops up at the bottom of the app. As you can see, I\'ve set the colors from white to clear, but th

7条回答
  •  盖世英雄少女心
    2021-02-01 12:15

    As many, I still got a gray colour despite using a clear white.

    So I changed my approach and went for a mask rather than a gradient. End result is the same, well, better, since this one works in all situations, not just if you got a suitable background.

    I did not try this code with IB, but hopefully it works as well. Just set backgroundColor and you are good to go.

    @IBDesignable
    class FadingView: UIView {
    
        @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
        @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
        @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
        @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}
        @IBInspectable var invertMode:      Bool =  false { didSet { updateColors() }}
    
        private let gradientLayerMask = CAGradientLayer()
    
        private func updatePoints() {
            if horizontalMode {
                gradientLayerMask.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
                gradientLayerMask.endPoint   = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
            } else {
                gradientLayerMask.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
                gradientLayerMask.endPoint   = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
            }
        }
    
        private func updateLocations() {
            gradientLayerMask.locations = [startLocation as NSNumber, endLocation as NSNumber]
        }
    
        private func updateSize() {
            gradientLayerMask.frame = bounds
        }
    
        private func updateColors() {
            gradientLayerMask.colors = invertMode ? [UIColor.white.cgColor, UIColor.clear.cgColor] : [UIColor.clear.cgColor, UIColor.white.cgColor]
        }
    
        private func commonInit() {
            layer.mask = gradientLayerMask
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            commonInit()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            updatePoints()
            updateLocations()
            updateSize()
            updateColors()
        }
    }
    

提交回复
热议问题