Would like to know create drop shadow for UINavigationbar. I tried to create custom navigation bar background with drop shadow, but the drop shadow cover the background view
In applyDefaultStyle
, try adding this line:
self.layer.masksToBounds = NO;
The default value for this property is YES
, which means that even though the shadow is rendered, it won't be rendered outside the bounds of the view, which means effectively that you don't see it at all.
If you're animating this view in any way, you should also add this line:
self.layer.shouldRasterize = YES;
... unless you want the animation to be slow and jerky.
If you apply a drop shadow to a UINavigationBar
, the shadow is clipped at below the corners:
This is just how shadows behave on rectangles. I usually create a path for the shadow that's a bit wider than the actual nav bar, which creates an effect that is more like what you'd generally expect:
@implementation UINavigationBar (DropShadow)
-(void)willMoveToWindow:(UIWindow *)newWindow {
[super willMoveToWindow:newWindow];
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOpacity = 1;
self.layer.shadowOffset = CGSizeMake(0,4);
CGRect shadowPath = CGRectMake(self.layer.bounds.origin.x - 10, self.layer.bounds.size.height - 6, self.layer.bounds.size.width + 20, 5);
self.layer.shadowPath = [UIBezierPath bezierPathWithRect:shadowPath].CGPath;
self.layer.shouldRasterize = YES;
}
I stick the shadow drawing code into a function to keep loadView clean. You could pass in the object you want to draw the shadow on if you wanted all your shadows consistent.
- (void)loadView
{
self.view = [[UIView alloc] init];
self.view.backgroundColor = [UIColor whiteColor];
[self drawShadow];
}
- (void)drawShadow
{
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.layer.shadowOpacity = 0.3;
self.navigationController.navigationBar.layer.shadowOffset = CGSizeMake(0, 0);
self.navigationController.navigationBar.layer.shadowRadius = 15;
self.navigationController.navigationBar.layer.masksToBounds = NO;
}
Since iOS 6.0, UINavigationBar has a property shadowImage:
@property(nonatomic,retain) UIImage *shadowImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
which of course greatly simplifies this very common task :D