I'm trying to add a gradient in order to fade in and out text for my UIScrollView. I got the suggestion to add a CAGradientLayer. I thought I would do something like this for start, and just cover the whole thing versus worry about the top and bottom portions since I'm new to gradients and drawing in general. I tried this, but I don't think it's correct since my UILabel text in my UIScrollView looks unchanged. Am I on the right track? Thanks.
Edit:
CAGradientLayer *gradient = [CAGradientLayer layer];
CGColorRef darkColor = [[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6] CGColor];
// CGColorRef darkColor = [[self.scrollView.backgroundColor colorWithAlphaComponent:0.5] CGColor];
// CGColorRef lightColor = [[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.6] CGColor];
CGColorRef lightColor = [[self.scrollView.backgroundColor colorWithAlphaComponent:1.0] CGColor];
CGRect gradientFrame = self.scrollView.bounds;
gradientFrame.size.height = 50;
gradient.frame = gradientFrame;
gradient.colors = [NSArray arrayWithObjects: (id)darkColor, (id)lightColor, nil];
[self.scrollView.layer addSublayer:gradient];
I've tried this a few different ways using different RGB, alpha values, and I can't get it look right just to have the text fade out. I tried the backgroundColor with alpha from 0.0 to 1.0 and I do not see any changes.
If you add the gradient to the scrollview it will scroll away with the scrollview. Adding it to the scrollviews superview should do the trick.
It still should be visible initially if it is big enough.
This works for me:
+ (CAGradientLayer *)maskWithHorizontalFadingBordersWithinBounds:(CGRect)bounds
{
CAGradientLayer * maskLayer = [CAGradientLayer layer];
id outerColor = (id)[UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
id innerColor = (id)[UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
maskLayer.colors = @[outerColor, innerColor, innerColor, outerColor];
maskLayer.locations = @[@0.0 , @0.025 , @0.975 , @1.0];
maskLayer.bounds = bounds;
maskLayer.anchorPoint = CGPointZero;
return maskLayer;
}
Call this method within the appropiate initializer, be careful not to create the layer more often than necessary.
scrollViewsSuperView.layer.mask = [CAGradientLayer maskWithHorizontalFadingBordersWithinBounds:scrollView.bounds];
Disadvantage: The Scrollbars will be affected too, I still prefer this simple solution.
Alternative: Add the mask as a sublayer to the scroll view itself and reset its position to 0 in scrollViewDidScroll.