tags:

views:

2568

answers:

1

I'm trying to add a small shadow to an image, much like the icon shadows in the App Store. Right now I'm using the following code to round the corners of my images. Does anyone know how I can adapt it to add a small shadow?

- (UIImage *)roundCornersOfImage:(UIImage *)source height:(int)height width:(int)width  {
int w = width;
int h = height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef imageContext = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

CGContextBeginPath(imageContext);

CGRect rect = CGRectMake(0, 0, w, h);
addRoundedRectToPath(imageContext, rect, 10, 10);
CGContextClosePath(imageContext);
CGContextClip(imageContext);

CGContextDrawImage(imageContext, CGRectMake(0, 0, w, h), source.CGImage);

CGImageRef imageMasked = CGBitmapContextCreateImage(imageContext);
CGContextRelease(imageContext);
CGColorSpaceRelease(colorSpace);

return [UIImage imageWithCGImage:imageMasked];    
}

"addRoundedRectToPath" refers to another method that obviously rounds the corners.

+1  A: 

First, here's a link to the documentation:

http://developer.apple.com/iPhone/library/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadows/dq_shadows.html#//apple_ref/doc/uid/TP30001066-CH208-TPXREF101

Next, try adding something like this right before the call to CGContextDrawImage(...):

CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
CGColorRef shadowColor = CGColorCreate(colorSpace, components);
CGContextSetShadowWithColor(imageContext, 3, 3, 2, shadowColor);
CGRelease(shadowColor);

After, the call to CGContextSetShadowWithColor(...), everything should draw with a shadow that is offset by (3, 3) points, and drawn with a 2.0 point blur radius. You'll probably want to tweak the opacity of the black color (the forth component in components), and change the shadow parameters.

If you'd like to stop drawing with a shadow at some point, you need to save the graphics context before calling CGContextSetShadowWithColor, and restore it when you want to stop drawing with a shadow.

Jon Hess
argument 2 of CGContextSetShadowWithColor is CGSize. Therefore it should be CGContextSetShadowWithColor(imageContext, CGSizeMake(3,3), 2, shadowColor);
Sam V