Looking up a completely separate problem, I was running across a considerable amount of people asking how to apply a drop shadow to a UIView or how to round the corners. I previously did a post on something similar, but I wanted to take the time and build a small demo that shows how to accomplish both these things in a very easy way. Essentially we’re going to use the CALayer in the UIView to do all the work for us and not even bother with renderInContext:UIGraphicsGetCurrentContext(). Suppose we have a view we want to round and apply a drop shadow to called roundedView. The following lines will not only give us a nice shadow, but will also give the view slight rounded corners. Doing it this way also causes the shadow to have the rounded as well.
CALayer *iconlayer = roundedView.layer;
iconlayer.masksToBounds = NO;
iconlayer.cornerRadius = 8.0;
iconlayer.shadowOffset = CGSizeMake(-5.0, 5.0);
iconlayer.shadowRadius = 5.0;
iconlayer.shadowOpacity = 0.6;
Extremely simple and not many lines of code. If you know that you’re going to always apply this to certain views, then you could add this code to the drawRect:(CGRect)rect method of your UIView subclass. This would be bit more efficient too. Also, if you’re worried about efficiency, you can add iconlayer.shouldRasterize. This will create a cached bitmap of the shadow so it won’t have to recalculate it again. However, if you’re going to be modifying the shadow parameters or if you’re worried about shadow quality then you might want to leave that off.
Well, that’s it, be sure to grab the code and play around with the effects. CALayers make it really easy to get some cool effects on your UIViews and there’s a lot more you can do with them, but that’s maybe for another post. Questions and comments are always welcomed.