Search code examples
ioscore-graphicscalayer

CAGradientLayer covers everything drawn in drawRect


I have the following code:

-(void)drawRect:(CGRect)rect
{

    // gradient background
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = rect;
    gradient.colors = [NSArray arrayWithObjects:(id) backgroundGradientTop.CGColor, (id) backgroundGradientBottom.CGColor, nil];
    gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7], nil];

    [self.layer insertSublayer:gradient atIndex:0];



    // line on top
    [[UIColor redColor] set];

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(currentContext, 5.0f);

    CGContextMoveToPoint(currentContext, 0, 10.0f);

    CGContextAddLineToPoint(currentContext, rect.size.width, 10.0f);

    CGContextStrokePath(currentContext);


}

the line i'm trying to draw on top of the gradient is never shown. If i comment out the gradient layer it is there. Is there someway to draw both a gradient background and a line (or a few lines) on top? Maybe i shouldn't be mixing calayer and CG?


Solution

  • The line i'm trying to draw on top of the gradient is never shown. If i comment out the gradient layer it is there.

    That's because sublayers appear on top of their parent layers. Your gradient is apparently opaque, and the same size as your view, so it covers up the view.

    You can't mix CA and CG drawing this way. It would work better if you drew the gradient using CGContextDrawLinearGradient.