I am trying to add a CAGradientLayer in my drawRect, the code is the following:
- (void)drawRect:(CGRect)rect {
CAGradientLayer *gradientOverlay = [CAGradientLayer layer];
CGColorRef grayColor = [UIColor colorWithRed:37/255.f green:37/255.f
blue:37/255.f alpha:1.0].CGColor;
CGColorRef blueColor = [UIColor colorWithRed:23.0/255.0 green:171.0/255.0
blue:219.0/255.0 alpha:1.0].CGColor;
gradientOverlay.colors = [NSArray arrayWithObjects:
(id) grayColor,
(id) grayColor,
(id) blueColor,
nil];
gradientOverlay.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0],
[NSNumber numberWithFloat:0.4],
[NSNumber numberWithFloat:1],
nil];
CGPoint startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMidY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect));
gradientOverlay.startPoint = startPoint;
gradientOverlay.frame = self.bounds;
gradientOverlay.endPoint = endPoint;
self.layer.mask = gradientOverlay;
}
Any idea why this is not working?
Add your
CAGradientLayeras a sublayer of yourself.layer.Note: If you’re doing it in the
drawRect:method make sure you’re not adding a newCAGradientLayerevery timedrawRect:is called.UPDATE (regarding the comment):
Here’s the code for what you’re asking:
Note: You don’t have to do this in
drawRect:method. Create your layer hierarchy in theinitmethod for example, if you need to change the geometry of some views/layers override thelayoutSubviewsmethod.