Search code examples
objective-cioscore-graphicsdrawrect

draw a shadow around the shape,core graphic


I am drawing a shape with a stroke around it by doing following

- (void)drawRect:(CGRect)rect
{
    // Draw a cross rectagle
    CGContextRef    context     =   UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);

    CGContextBeginPath(context);
    CGContextMoveToPoint    (context, 190, 0);
    CGContextAddLineToPoint (context, 220, 0);
    CGContextAddLineToPoint (context, 300, 80);
    CGContextAddLineToPoint (context, 300, 110);
    CGContextClosePath(context);

    CGContextSetFillColorWithColor(context, bgColor);                           // fill color
    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);     // set color for stroke
    CGContextSetLineWidth(context, .8);                                         // set width for stroke
    CGContextDrawPath(context,  kCGPathFillStroke);                             // do fill and stroke together


    CGContextEOClip(context);
    CGContextSetShadowWithColor(context, CGSizeMake(1, 1), 1.0, [UIColor whiteColor].CGColor);
    CGContextSetBlendMode (context, kCGBlendModeScreen);
    CGContextRestoreGState(context);
}

and what I am ending up like below ( the cross flag )

enter image description here

Now this time, I would like to drop some shadow around the cross flag as well.

What should I do to achieve this. Please advice me on this issue. Thanks.


Solution

  • CGContextSetShadow or CGContextSetShadowWithColor (documentation 1, documentation 2)

    In your case, I was able to get a shadow via

    ...
    CGContextSaveGState(context);
    
    CGContextSetShadowWithColor(context, CGSizeMake(-3 , 2), 4.0, [UIColor whiteColor].CGColor);
    
    CGContextBeginPath(context);
    CGContextMoveToPoint    (context, 190, 0);
    ...
    

    And I removed these from the bottom (clip wasn't doing anything here, why the blend mode?)

    CGContextEOClip(context);
    CGContextSetShadowWithColor(context, CGSizeMake(1, 1), 1.0, [UIColor whiteColor].CGColor);
    CGContextSetBlendMode (context, kCGBlendModeScreen);