segmentView文字颜色渐变的方法
2019-06-25 本文已影响0人
Vaja_wlu
segment作为常用控件,在APP应用非常广泛,今天分享一个segment的title颜色渐变的方法,使应用具有更好的用户体验。
oldTitleView.textColor = [UIColor
colorWithRed:[self.selectedColorRGBA[0] floatValue] + [self.deltaRGBA[0] floatValue] * progress
green:[self.selectedColorRGBA[1] floatValue] + [self.deltaRGBA[1] floatValue] * progress
blue:[self.selectedColorRGBA[2] floatValue] + [self.deltaRGBA[2] floatValue] * progress
alpha:[self.selectedColorRGBA[3] floatValue] + [self.deltaRGBA[3] floatValue] * progress];
currentTitleView.textColor = [UIColor
colorWithRed:[self.normalColorRGBA[0] floatValue] - [self.deltaRGBA[0] floatValue] * progress
green:[self.normalColorRGBA[1] floatValue] - [self.deltaRGBA[1] floatValue] * progress
blue:[self.normalColorRGBA[2] floatValue] - [self.deltaRGBA[2] floatValue] * progress
alpha:[self.normalColorRGBA[3] floatValue] - [self.deltaRGBA[3] floatValue] * progress];
CGFloat deltaScale = self.titleBigScale - 1.0;
oldTitleView.currentTransformSx = self.titleBigScale - deltaScale * progress;
currentTitleView.currentTransformSx = 1.0 + deltaScale * progress;
其中titleBigScale为标题缩放倍数,可根据情况自行设定;process为滑动比例,通过以下方法计算:
CGFloat tempProgress = scrollView.contentOffset.x / self.bounds.size.width;
NSInteger tempIndex = tempProgress;
CGFloat progress = tempProgress - floor(tempProgress);
其中颜色相关方法如下:
- (NSArray *)deltaRGBA {
if (_deltaRGBA == nil) {
NSArray *normalColorRgb = self.normalColorRGBA;
NSArray *selectedColorRgb = self.selectedColorRGBA;
NSArray *delta;
if (normalColorRgb && selectedColorRgb) {
CGFloat deltaR = [normalColorRgb[0] floatValue] - [selectedColorRgb[0] floatValue];
CGFloat deltaG = [normalColorRgb[1] floatValue] - [selectedColorRgb[1] floatValue];
CGFloat deltaB = [normalColorRgb[2] floatValue] - [selectedColorRgb[2] floatValue];
CGFloat deltaA = [normalColorRgb[3] floatValue] - [selectedColorRgb[3] floatValue];
delta = [NSArray arrayWithObjects:@(deltaR), @(deltaG), @(deltaB), @(deltaA), nil];
_deltaRGBA = delta;
}
}
return _deltaRGBA;
}
- (NSArray *)normalColorRGBA {
if (!_normalColorRGBA) {
NSArray *normalColorRGBA = [self getColorRGBA:self.segmentStyle.normalTitleColor];
NSAssert(normalColorRGBA, @"设置普通状态的文字颜色时 请使用RGBA空间的颜色值");
_normalColorRGBA = normalColorRGBA;
}
return _normalColorRGBA;
}
- (NSArray *)selectedColorRGBA {
if (!_selectedColorRGBA) {
NSArray *selectedColorRGBA = [self getColorRGBA:self.segmentStyle.selectedTitleColor];
NSAssert(selectedColorRGBA, @"设置选中状态的文字颜色时 请使用RGBA空间的颜色值");
_selectedColorRGBA = selectedColorRGBA;
}
return _selectedColorRGBA;
}
- (NSArray *)getColorRGBA:(UIColor *)color {
CGFloat numOfcomponents = CGColorGetNumberOfComponents(color.CGColor);
NSArray *rgbaComponents;
if (numOfcomponents == 4) {
const CGFloat *components = CGColorGetComponents(color.CGColor);
rgbaComponents = [NSArray arrayWithObjects:@(components[0]), @(components[1]), @(components[2]), @(components[3]), nil];
}
return rgbaComponents;
}
具体效果如下:
未命名.gif