1.前言:最近项目首页改版,用到了这个NavigationBar渐变,效果如下。
原来在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
新人求鼓励 厚着脸皮要个星。