views:

558

answers:

1

filling a path with a solid color is easy enough:

CGPoint aPoint;
for (id pointValue in points)
{
    aPoint = [pointValue CGPointValue];
    CGContextAddLineToPoint(context, aPoint.x, aPoint.y);
}
[[UIColor redColor] setFill];
[[UIColor blackColor] setStroke];
CGContextDrawPath(context, kCGPathFillStroke);

I'd like to draw a gradient instead of solid red, but I am having trouble. I've tried the code listed in the Question/Answer: http://stackoverflow.com/questions/422066/gradients-on-uiview-and-uilabels-on-iphone

which is:

CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:rect];
[gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor],
                (id)[[UIColor whiteColor] CGColor], nil]];
[[self layer] setMasksToBounds:YES];

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

However, this paints the entire view that this is in with the gradient, covering up my original path.

+4  A: 

I would clip to the path you want to fill, and use CGContextDrawLinearGradient. Here is a simple implementation of drawRect: as an example:

- (void) drawRect:(CGRect)rect
{
    // Create a gradient from white to red
    CGFloat colors [] = { 
        1.0, 1.0, 1.0, 1.0, 
        1.0, 0.0, 0.0, 1.0
    };

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient), gradient = NULL;

    CGContextRestoreGState(context);

    CGContextAddEllipseInRect(context, rect);
    CGContextDrawPath(context, kCGPathStroke);
}
sbooth
If I could give you an awesome badge I would!Do you know of any tutorials on the CGContextSaveGState and stuff? Because the apple class reference is kind of thin.
Derrick
Derrick: The Quartz 2D Programming Guide covers that, along with everything else: http://developer.apple.com/mac/library/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html#//apple_ref/doc/uid/TP30001066-CH202-TPXREF132
Peter Hosey
After using your example code, my shadow has disappeared. I've tried relocating the shadow line ("CGContextSetShadow(context, CGSizeMake(5.0, -5.0), 4);") before the gstate save, after it, befroe the gstate restore, after it, before and after the clipping - nothing helped.
Doron
same for stroke
Doron