views:

568

answers:

2

I'm drawing a rounded image in a UITableView cell like so:

CGRect imageRect = CGRectMake(8, 8, 40, 40);
CGFloat radius = 3;

CGFloat minx = CGRectGetMinX(imageRect);
CGFloat midx = CGRectGetMidX(imageRect);
CGFloat maxx = CGRectGetMaxX(imageRect);
CGFloat miny = CGRectGetMinY(imageRect);
CGFloat midy = CGRectGetMidY(imageRect);
CGFloat maxy = CGRectGetMaxY(imageRect);

CGContextMoveToPoint(context, minx, midy);
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
CGContextClosePath(context);

CGContextClip(context);

[self.theImage drawInRect:imageRect];

This looks great, but I'd like to add a shadow to it for added effect. I've tried using something along the lines of:

CGContextSetShadowWithColor(context, CGSizeMake(2, 2), 2, [[UIColor grayColor] CGColor]);
CGContextFillPath(context);

But this only works when the image has transparent areas, if the image isn't transparent at all, it won't even draw a shadow around the border.

I'm wondering if there is something I'm doing wrong?

A: 

I'd imagine that if the image you're drawing to has no transparent areas then CoreGraphics interprets the whole image as a solid object. Then if it tries to draw a shadow the shadow will be draw outside the bounds of the image and as such you will not see it.

This page provides a good example of how to do such drawing with CoreGraphics. Perhaps you could try modifying the code provided there and see if that solves your problem.

pheelicks
The only thing I could pick up from that page was that I can use CGContextSetShadow (context, CGSizeMake(1, -1), 3); instead of what I was using before. I'm still unclear on how I can draw the shadow outside the rects of the image if the image doesn't have any transparency at all.
Tom Irving
+1  A: 

Turns out the correct way to do this is by clipping the UIImage itself rather than the path. It's then a simple matter of:

CGContextSetShadow(...);
[self.theClippedImage drawInRect:...];
Tom Irving