Cocoa draw image with rounded corners and shadow

clipcocoacore-graphicsshadow

I am trying to draw an image using core graphics such that it has rounded corners and a drop shadow. Here is a snippet of my code:

CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 2, shadowColor);    
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawImage(context, rect, image);

The problem I am having is that the clipping to create the rounded corners is also clipping the shadow. Since the image may be transparent in areas, I cannot simply draw the rounded rectangle with a shadow under the image. I guess I need to apply the rounded shape to the image first, and then draw the resulting image to the screen and add the shadow. Does anyone know how to do this?

Thanks!

Best Answer

Okay, so assuming that you have a UIView subclass, which has an instance variable, image, which is a UIImage, then you can do your drawRect: function like so...

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGRect _bounds = [self bounds];
    CGColorRef aColor;
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Create a path
    CGRect insetRect = CGRectInset(_bounds, kBSImageButtonBorder, kBSImageButtonBorder);
    CGRect offsetRect = insetRect; offsetRect.origin = CGPointZero;

    UIGraphicsBeginImageContext(insetRect.size);
    CGContextRef imgContext = UIGraphicsGetCurrentContext();
    CGPathRef clippingPath = [UIBezierPath bezierPathWithRoundedRect:offsetRect cornerRadius:CORNER_RADIUS].CGPath; 
    CGContextAddPath(imgContext, clippingPath);
    CGContextClip(imgContext);  
    // Draw the image
    [image drawInRect:offsetRect];
    // Get the image
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Setup the shadow
    aColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f].CGColor;
    CGContextSetShadowWithColor(context, CGSizeMake(0.0f, 2.0f), 2.0f, aColor);     

    // Draw the clipped image in the context
    [img drawInRect:insetRect];

}

I'm a little new to Quartz programming myself, but that should give you your image, centered in the rectangle, minus a border, with a corner radius, and a 2.f point shadow 2.f points below it. Hope that helps.

Related Topic