Add shadow to UIImage drawn in rounded path
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?
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:...];
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.
精彩评论