24

I’m looking to fade out a scrolling UITextView over a background image, something similar to the gradient at the top of this little example.

enter image description here

I’m trying to work out how I can achieve this using CAGradientLayer and masks. As the text in the view scrolls (vertically), I need the text to become transparent before it hits the frame of the view, to give the illusion that it’s fading out upward and downward.

Any tips on how I might achieve this?

Luke
  • 9,512
  • 15
  • 82
  • 146

3 Answers3

43

Oh man, I use this a lot. Have it saved as a snippet:

CAGradientLayer *gradient = [CAGradientLayer layer];

gradient.frame = self.textView.superview.bounds;
gradient.colors = @[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor, (id)[UIColor blackColor].CGColor, (id)[UIColor clearColor].CGColor];
gradient.locations = @[@0.0, @0.03, @0.97, @1.0];

self.textView.superview.layer.mask = gradient;

This solution requires that your text view be embedded in a view of its own. This applies a 3% fade to the top and bottom of the text view. Modify gradient.locations to your needs.

duci9y
  • 4,128
  • 3
  • 26
  • 42
8

I've been inspired by others from this thread, but have converted the code to Swift and used start and end point instead, to make a gradient at the bottom.

if let containerView = textView.superview {
    let gradient = CAGradientLayer(layer: containerView.layer)
    gradient.frame = containerView.bounds
    gradient.colors = [UIColor.clearColor().CGColor, UIColor.blueColor().CGColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 0.85)
    containerView.layer.mask = gradient
    }

See: image of textView bottom with gradient

Andrej
  • 7,266
  • 4
  • 38
  • 57
1

Swift 5

Taking the code of Andrej and updating it for Swift 5

if let containerView = textView.superview {
    let gradient = CAGradientLayer(layer: containerView.layer)
    gradient.frame = containerView.bounds
    gradient.colors = [UIColor.clear.cgColor, UIColor.blue.cgColor]
    //the line above is update for swift 5
    gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 0.85)
    containerView.layer.mask = gradient
    }
codeameya
  • 19
  • 3