Effectively render a Drop Shadow on a UIView subclass

Adding a drop shadow to your UIView subclass is as easy as the following code.

UIView *customView = [[UIView alloc] init];
...
customView.layer.shadowColor    = [[UIColor lightGrayColor] CGColor];
customView.layer.shadowOffset   = CGSizeMake(1, 1);
customView.layer.shadowOpacity  = 1.0;
customView.layer.shadowRadius   = 2.0; 
... 

While the common use case of such trick is on rendering stationary views, and no doubt it works perfectly that way, placing them inside a scrollable view like UISrollView or UITableView yields a different feel - it lags a bit when scrolling. So the way to solve this issue and keep them scrolling smoothly is to make use of UIBezierPath. You create an instance of this based on the `bounds` of the receiving view. Then set it as the `shadowPath` of the view's layer object.

UIBezierPath *path  = [UIBezierPath bezierPathWithRect:customView.bounds];
customView.layer.shadowPath = [path CGPath];

Now let's modify our base code to include the bezier path.

UIView *customView = [[UIView alloc] init];
...
UIBezierPath *path  = [UIBezierPath bezierPathWithRect:customView.bounds];
customView.layer.shadowPath = [path CGPath];

customView.layer.shadowColor    = [[UIColor lightGrayColor] CGColor];
customView.layer.shadowOffset   = CGSizeMake(1, 1);
customView.layer.shadowOpacity  = 1.0;
customView.layer.shadowRadius   = 2.0; 
... 

0 comments :

Post a Comment

Hi there! Please leave your message here. Also, I may not be able to respond to your query right away. So please bear with me. Thanks. :)