主要实现原理:在导航栏的的位置上放置一个自定义的view,通过手势操作来改变透明度.
自定义的view(通过绘图的方式):
```javascript
- (void)drawRect:(CGRect)rect {
UIBezierPath*rectPath = [UIBezierPathbezierPathWithRect:rect];
[[UIColorwhiteColor]set];
[rectPathfill];
//画线
// 1个点--> 2个像素(4s, 5, 6)
// 1个点--> 3个像素
//线高度
CGFloatlineH =1/[UIScreenmainScreen].scale;
CGFloatlineY = rect.size.height- lineH;
UIBezierPath*linePath = [UIBezierPathbezierPath];
//线的起点
[linePathmoveToPoint:CGPointMake(0, lineY)];
[linePathaddLineToPoint:CGPointMake(rect.size.width, lineY)];
[[UIColorpurpleColor]set];
[linePathstroke];
}
```
定义一些属性:
YMSView即为自定义的view,作为新的导航栏,也就类似于一个遮罩的效果
myAlpha 作为修改导航栏的透明度(自定义的view)
mycolor是用来修改导航栏字体的颜色
imageview用来操作的一张图片
懒加载的形式加载这个自定义的view
/导航栏view
-(YMSView*)myNavView
{
if(_myNavView==nil)
{
//64正好覆盖住原来的view
YMSView*navView = [[YMSViewalloc]initWithFrame:CGRectMake(0,0, [UIScreenmainScreen].bounds.size.width,64)];
navView.backgroundColor= [UIColorwhiteColor];
navView.alpha=0;
[self.viewaddSubview:navView];
_myNavView= navView;
}
return_myNavView;
}
给当前的根view添加拖拽手势
-(void)addPanGesture
{
UIPanGestureRecognizer*panGesture = [[UIPanGestureRecognizeralloc]initWithTarget:selfaction:@selector(pan:)];
[self.viewaddGestureRecognizer:panGesture];
}
如何才能改变当前导航栏的透明度和标题颜色呢?
关节点就在拖拽手势的实现中,通过拖拽距离来设置一个比例,在拖动中来动态改变
-(void)pan:(UIPanGestureRecognizer*)pan
{
//获取当前拖拽的距离
CGPointloc = [pantranslationInView:pan.view];
//让view的tansform归零,否则会一直叠加
[pansetTranslation:CGPointZeroinView:pan.view];
//更新图片的约束
[_imageViewmas_updateConstraints:^(MASConstraintMaker*make) {
//计算图片滚动的距离
CGFloatdistance =_imageView.height+ loc.y;
//放置图片穿透到上面或者下拖拽的时候放大
//判断滚动的距离
//此处判断特别重要,这样能解决拖拽过程中卡顿的现象
防止向下拖拽时放大图片
if(distance >200)
{
return;
}
make.height.mas_equalTo(distance);
}];
//根据拖动的距离来改变导航栏的颜色
CGFloatmax =200;
CGFloatmin =64;
//求出颜色变化范围
CGFloatcover = max - min;
//计算比例
//根据imageview高度的变化来计算
CGFloatscale =1- (_imageView.height- min)/cover;
//NSLog(@"%lf",_imageView.height);
self.myAlpha= scale;
self.mycolor=1-scale;
}
记得开始定义了一个透明度和颜色的属性,通过重写set方法,并在其中改变自定义view的透明度和字体的颜色
//导航栏矩形的透明度修改
-(void)setMyAlpha:(CGFloat)myAlpha
{
_myAlpha= myAlpha;
self.myNavView.alpha= myAlpha;
}
-(void)setMycolor:(CGFloat)mycolor
{
_mycolor= mycolor;
//设置文字的颜色
[self.navigationController.navigationBarsetTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColorcolorWithWhite:mycoloralpha:1]}];
//设置导航栏的渲染颜色
[self.navigationController.navigationBarsetTintColor:[UIColorcolorWithWhite:mycoloralpha:1]];
}
效果图:
还有很多小细节没有处理好,希望大家看到后能够指出,一起分享下经验^_^ ^_^