Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing shadow with Quartz is slow on iPhone & iPad. Another way?

I was pretty excited when I found out just how easy it is to add shadows to my UIViews on the iPhone/iPad.

Just add the framework in Xcode, add the import to the top of the file:

#import <QuartzCore/QuartzCore.h>

Then later:

self.contentView.layer.shadowRadius = 3.0;
self.contentView.layer.shadowOffset = CGSizeMake(-2.0, -3.0);
self.contentView.layer.shadowOpacity = 0.5;
self.contentView.layer.shadowColor = [UIColor blackColor].CGColor;

While this does create a beautiful shadow in my app, it also lags it to death now when the view is shown... even when launched outside of the debugger. Is there something I'm forgetting or is this method just not practical for larger views?

For reference, I posted a screenshot here.

like image 297
Moduspwnens Avatar asked Sep 09 '10 14:09

Moduspwnens


2 Answers

You should set the shadowPath property. It is how CoreGraphics is able to optimize shadows.

For example, if your view is an opaque rectangle:

self.contentView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.contentView.bounds].CGPath;
like image 100
cobbal Avatar answered Nov 15 '22 15:11

cobbal


Thought I should make an answer because I didn't want this gem to get buried in the comments.

In addition to cobbal's answer above, which helped a lot, occulus also mentioned the following optimization for non-rectangular shadows, such as text shadows.

self.contentView.layer.shouldRasterize = YES;
// Fix visual degradation when rasterizing on high-density screens:
self.contentView.layer.rasterizationScale = [[UIScreen mainScreen] scale];
like image 41
Thane Brimhall Avatar answered Nov 15 '22 14:11

Thane Brimhall