网易导航条渐变效果核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 滚动中调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetX = scrollView.contentOffset.x;
// 取出左右两个button的index
NSInteger leftIndex = offsetX / ZHJScreenW;
NSInteger rightIndex = leftIndex + 1;
// 取出左边的button
UIButton *leftButton = self.buttons[leftIndex];

// 取出右边的button,考虑到在最右边的时候不用再滑动了,所以要判断下
UIButton *rightButton = nil;
if (rightIndex < self.buttons.count) {
rightButton = self.buttons[rightIndex];
}
// 取出左边的缩放值
CGFloat scaleR = offsetX / ZHJScreenW - leftIndex;
// 取出右边的缩放值
CGFloat scaleL = 1 - scaleR;

// maxTitleScale = 1.3 是最大缩放大小
CGFloat transScale = maxTitleScale - 1;
leftButton.transform = CGAffineTransformMakeScale(scaleL * transScale + 1, scaleL * transScale + 1);

rightButton.transform = CGAffineTransformMakeScale(scaleR * transScale + 1, scaleR * transScale + 1);

// 用rgb来实现颜色的渐变
UIColor *rightColor = [UIColor colorWithRed:scaleR green:scaleR blue:scaleR alpha:1];
UIColor *leftColor = [UIColor colorWithRed:scaleL green:scaleL blue:scaleL alpha:1];

[leftButton setTitleColor:leftColor forState:UIControlStateNormal];
[rightButton setTitleColor:rightColor forState:UIControlStateNormal];

// 设置指示器的位置
// 算出button的宽度
CGFloat buttonW = (self.view.width - 100) / 3.0;
// 设置动画
self.indicator.transform = CGAffineTransformMakeTranslation(buttonW * (offsetX / ZHJScreenW), 0);

}