Fading out any content which approaches edges of UIScollView

Alessandro picture Alessandro · May 31, 2013 · Viewed 9.2k times · Source

As the title says, I am trying to give to some UIImageViews a fading out effect as they get closer and closer to any of the four edges of my UIScrollView. Since the user can drag the UIImages, if he drags them towards the edges, they start fading out, instead of giving that cut out effect as if there were borders to the UIScrollView. I tried this tutorial:

http://www.cocoanetics.com/2011/08/adding-fading-gradients-to-uitableview/

suggested in another stack overflow question, but it can only be applied to UITableViews. I would like the image to start fading as it gets one centimeter away from the border.

Answer

Nate picture Nate · Jun 1, 2013

Similar to what was done in the Cocoanetics post you link to, you can create a CAGradientLayer to cover your scroll view. Make it fade out to the left, right, top and bottom edges, using the background color of your scroll view (in my example, white):

   CGColorRef innerColor = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
   CGColorRef outerColor = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;

   // first, define a horizontal gradient (left/right edges)
   CAGradientLayer* hMaskLayer = [CAGradientLayer layer];
   hMaskLayer.opacity = .7;
   hMaskLayer.colors = [NSArray arrayWithObjects:(id)outerColor,
                        (id)innerColor, (id)innerColor, (id)outerColor, nil];
   hMaskLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
                           [NSNumber numberWithFloat:0.15],
                           [NSNumber numberWithFloat:0.85],
                           [NSNumber numberWithFloat:1.0], nil];
   hMaskLayer.startPoint = CGPointMake(0, 0.5);
   hMaskLayer.endPoint = CGPointMake(1.0, 0.5);
   hMaskLayer.bounds = self.scrollView.bounds;
   hMaskLayer.anchorPoint = CGPointZero;

   CAGradientLayer* vMaskLayer = [CAGradientLayer layer];
   // without specifying startPoint and endPoint, we get a vertical gradient
   vMaskLayer.opacity = hMaskLayer.opacity;
   vMaskLayer.colors = hMaskLayer.colors;
   vMaskLayer.locations = hMaskLayer.locations;
   vMaskLayer.bounds = self.scrollView.bounds;
   vMaskLayer.anchorPoint = CGPointZero;

   // you must add the masks to the root view, not the scrollView, otherwise
   //  the masks will move as the user scrolls!
   [self.view.layer addSublayer: hMaskLayer];
   [self.view.layer addSublayer: vMaskLayer];

Disclaimer: this does sort of double-up the gradient/fade at the four corners. You can take a look at the results and decide whether they're good enough for you. If not, you could also try drawing a transparent image in something like Photoshop, and adding a UIImageView subview on top as the mask, using the image you drew.

enter image description here

Youtube screen capture