Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a Shadow after the CGContextClip with Core Graphics

UPDATE: I tried implementing the method specified by Peter and am getting incorrect shadowing. What is wrong?

alt text http://grab.by/2XyP

CGContextSetShadowWithColor(c, CGSizeMake(4, 4), kAudioThumbShadowBlur, [[UAColor blackColor] CGColor]);
    CGContextFillPath(c);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, minx, midy);
    CGPathAddArcToPoint(path, NULL, minx, miny, midx, miny, kDefaultMargin);
    CGPathAddArcToPoint(path, NULL, maxx, miny, maxx, midy, kDefaultMargin);
    CGPathAddArcToPoint(path, NULL, maxx, maxy, midx, maxy, kDefaultMargin);
    CGPathAddArcToPoint(path, NULL, minx, maxy, minx, midy, kDefaultMargin);
    CGPathCloseSubpath(path);


    // Fill and stroke the path
    CGContextSaveGState(c);
    CGContextAddPath(c, path);
    CGContextClip(c);


    myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, 2);
    CGContextDrawLinearGradient(c, myGradient, CGPointMake(minx,miny), CGPointMake(minx,maxy), 0);

    CGContextAddPath(c, path);
    CGPathRelease(path);
    CGContextStrokePath(c);
    CGContextRestoreGState(c);





ORIGINAL QUESTION: I am looking to draw a natural looking shadow around the bottom of a custom rounded cell item I make in CoreGraphics using this code:

...
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, minx, miny);
    CGPathAddArcToPoint(path, NULL, minx, maxy, midx, maxy, kDefaultMargin);
    CGPathAddArcToPoint(path, NULL, maxx, maxy, maxx, miny, kDefaultMargin);
    CGPathAddLineToPoint(path, NULL, maxx, miny);
    CGPathAddLineToPoint(path, NULL, minx, miny);
    CGPathCloseSubpath(path);

    // Fill and stroke the path
    CGContextSaveGState(c);
    CGContextAddPath(c, path);
    CGContextClip(c);

    myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, 2);
    CGContextDrawLinearGradient(c, myGradient, CGPointMake(minx,miny), CGPointMake(minx,maxy), 0);

    CGContextAddPath(c, path);
    CGPathRelease(path);
    CGContextStrokePath(c);
    CGContextRestoreGState(c);
...

I want to apply the shadow around the outside of this path, either before or after the gradient fill. What is the best way to go about doing this?

like image 692
coneybeare Avatar asked Jan 19 '26 08:01

coneybeare


1 Answers

A gradient draw doesn't count as a fill, so, first, set the shadow and do a solid-color fill. Then, draw over the solid-color fill with the gradient and clipped stroke.

like image 62
Peter Hosey Avatar answered Jan 21 '26 00:01

Peter Hosey