iosswiftuiviewuikitcagradientlayer

How to add one more CAGradientLayer to UIView?


I have a PopupView with a scrollable label (like Marquee type). Its scrolled inside a labelView, which is just a UIView.

I decided to add an effect of transparent gradient to the left and right sides of labelView using the following code:

    let gradientLayer = CAGradientLayer()
    
    gradientLayer.startPoint = CGPoint(x: 0, y: 0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0)
    gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor]
    gradientLayer.locations = [0, 0.2, 1]
    
    gradientLayer.frame = labelView.bounds
    labelView.layer.mask = gradientLayer

But the effect is visible only on the left side of the labelView. Right side is unchanged:

How can I apply the same gradient to the labelView right side?


Solution

  • You should change your start/end points and your color locations

    In a linear Gradient locations are relative points where [colors] are presented.

      0 0.2   0.8 1
      |--|-----|--|
    

    so from 0 to 0.2 (20% of total length) we will have a gradient of clear to white, then from 0.2 (20%) to 0.8 (80%) a gradient from white to white (solid white) and from 0.8 (80%) to 1 (100%) a gradient from white to clear color.

    From apple https://developer.apple.com/documentation/quartzcore/cagradientlayer/1462410-locations

    Discussion The gradient stops are specified as values between 0 and 1. The values must be monotonically increasing. If nil, the stops are spread uniformly across the range. Defaults to nil.

    When rendered, the colors are mapped to the output color space before being interpolated.

    let gradientLayer = CAGradientLayer()
    
    gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
    gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
    gradientLayer.locations = [0, 0.2, 0.8, 1]
    
    gradientLayer.frame = labelView.bounds
    labelView.layer.mask = gradientLayer
    

    After Updated answer

    enter image description here