iOS11 NavigationBar 渐变

作者: 萌闹闹sama丶 | 来源:发表于2017-12-06 15:17 被阅读636次

1.前言:最近项目首页改版,用到了这个NavigationBar渐变,效果如下。

Navigation.gif

原来在iOS11 之前是 基本上就一句话 技能搞定系统自带的Nav

 self.navigationController.navigationBar.subviews.firstObject.alpha = offset;

现在iOS11 后 上面那个直接控制透明度失效
控制导航条背景图片的透明度

//设置背景透明
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]  forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

写一个UIImage的分类方法 设置UImage 的透明度

- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, self.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    offset = scrollView.contentOffset.y;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"title_bg"] imageByApplyingAlpha:(offset / 200)>0.99?0.99:(offset / 200)] forBarMetrics:UIBarMetricsDefault];
}

demo
https://github.com/Xiaochou129129/XSQUINavigation

新人求鼓励 厚着脸皮要个星。

相关文章

网友评论

  • lanmoyingsheng:原来可以这样。。。:smile:
  • DeveloperTang:楼主 你这个导航栏渐变在iOS11上有个bug 就是当前渐变页面push到下一页面再pop回来的时候导航栏渐变失效了 变成了全透明 不知道你有没有碰到 有什么方案可以解决
    乱世先生:在- (void)viewWillAppear:(BOOL)animated;中重写
    [self.navigationController.navigationBar setBackgroundImage:[bgImage imageByApplyingAlpha:(offset / 200)>0.99?0.99:(offset / 200)] forBarMetrics:UIBarMetricsDefault];

本文标题:iOS11 NavigationBar 渐变

本文链接:https://www.haomeiwen.com/subject/jcpkixtx.html