How to create UINavigationBar drop shadow

后端 未结 4 1715
臣服心动
臣服心动 2020-12-22 21:09

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

相关标签:
4条回答
  • 2020-12-22 21:54

    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.

    0 讨论(0)
  • 2020-12-22 21:54

    If you apply a drop shadow to a UINavigationBar, the shadow is clipped at below the corners:

    clipped shadow

    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;
    }
    

    better

    0 讨论(0)
  • 2020-12-22 21:57

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 22:04

    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

    0 讨论(0)
提交回复
热议问题