Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask overlay on UIScrollView

how would you go about overlaying a mask image of sorts on top of a UIScrollView?

For example, I have an image with black on the left and right fading to white in the center. I'd like to use this so that the items in my scroll view gradually fade out to the sides and the center item is completely opaque.

Also, the background of the view the scrollview is placed on is an image (not a solid color) which is dynamic and can change.

Any ideas?

like image 744
Nick Avatar asked Apr 18 '11 22:04

Nick


1 Answers

Your question wound up being the best source I could find on the basic problem, so I decided to post my solution here.

If you add the mask directly to the scroll view, you wind up applying the mask to the content itself for some reason -- i. e. the transparency doesn't shift as you scroll. As per the suggestions of other posts, I put the gradient in a view over (or rather, containing) the scroll view. As a result, scrollContainer is a UIViewObject whose sole subview is the scroll view in question.

This mask is configured for left-to-right scrolling. You could change it to top to bottom by manipulating the start and end point properties of the gradient.

The one down side is that this also clips the scroll position bar indicator of the scroll view. Since my scenario doesn't need one, that's acceptable, but your mileage may vary.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = scrollView.bounds;
gradient.colors = [NSArray arrayWithObjects:
                   (id)[[UIColor colorWithWhite:0 alpha:0] CGColor],
                   (id)[[UIColor colorWithWhite:0 alpha:1] CGColor],
                   (id)[[UIColor colorWithWhite:0 alpha:1] CGColor],
                   (id)[[UIColor colorWithWhite:0 alpha:0] CGColor], nil];
gradient.locations=[NSArray arrayWithObjects:
                    [NSNumber numberWithFloat:0],
                    [NSNumber numberWithFloat:.1],
                    [NSNumber numberWithFloat:.9],
                    [NSNumber numberWithFloat:1], nil];
gradient.startPoint=CGPointMake(0, .5);
gradient.endPoint=CGPointMake(1, .5);
[scrollContainer.layer setMask:gradient];
like image 170
RonLugge Avatar answered Oct 29 '22 08:10

RonLugge