Add drop shadow to PNG using Cocoa
-
29-04-2021 - |
Question
I have some PNGs with transparent backgrounds that I would like to add shadows to programatically. I've seen examples of adding shadows to square objects, but haven't seen any with complex shapes.
So the two steps I think I'd have to do would be:
- Isolate the PNG shape
- Draw a shape behind the PNG that is blurred, faded, and offset.
I don't have much experience with drawing within Cocoa, so any insight on where to begin would be much appreciated!
Screenshot:
(source: iworkinprogress.com)
Solution
Simplest way is to call CGContextSetShadow
in your drawRect:
before you draw the images.
- (void)drawRect:(CGRect)invalidRect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetShadow(c, CGSizeMake(5.0f, 5.0f), 5.0f);
[myImage drawAtPoint:CGPointMake(50.0f, 50.0f)];
}
OTHER TIPS
I found this category to be very useful: UIImage+Shadow.m
I am not really a graphics person, but what about this: if you have a mask for these images, or if you can create one programatically, then you can probably use a blur function to add a shadow like effect.
Experiment in Photoshop/Acorn/Pixelmator?
Since you want shadows like they all have the same light source... it seems like you might actually be better off with an OpenGL view, that casts a light from above and the images would sit slightly above a flat plane to cast a shadow on. I'd look for 3D OpenGL frameworks that would let you add things pretty easily...