渐变色的滑动条效果网上实现方案有很多,方法都大同小异,就是用颜色组生成新的Image插入到UISlider中。
生成image的方法如下所示:
-(UIImage *)getGradientImageWithColors:(NSArray*)colors imgSize:(CGSize)imgSize
{
NSMutableArray *arRef = [NSMutableArray array];
for(UIColor *ref in colors) {
[arRef addObject:(id)ref.CGColor];
}
UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)arRef, NULL);
CGPoint start = CGPointMake(0.0, 0.0);
CGPoint end = CGPointMake(imgSize.width, imgSize.height);
CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}
然后使用以下方法完成image设置。
[self.slider setMinimumTrackImage:img forState:UIControlStateNormal];
使用上面提到的办法虽然可以生成渐变色,但要做到下图这样的效果却有些问题,在滑动的时候无法保证图片保持不动。
图片中渐变色滑动条的设置非常简单,直接使用CAGradientLayer来设置UISlider的Layer就可以实现,代码如下:
UISlider *slider = [[UISlider alloc] init];
//隐藏slider横条
[slider setMinimumTrackTintColor:[UIColor clearColor]];
[slider setMaximumTrackTintColor:[UIColor clearColor]];
// gradient
CAGradientLayer *gl = [CAGradientLayer layer];
gl.frame = CGRectMake(0,0,slider.size);
[slider.layer addSublayer:gl];
gl.startPoint = CGPointMake(0, 0.5);
gl.endPoint = CGPointMake(1, 0.5);
gl.colors = @[(__bridge id)[UIColor colorWithRed:164/255.0 green:155/255.0 blue:127/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:180/255.0 green:146/255.0 blue:121/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:135/255.0 green:110/255.0 blue:88/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:123/255.0 green:101/255.0 blue:80/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:104/255.0 green:89/255.0 blue:74/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:99/255.0 green:84/255.0 blue:71/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:104/255.0 green:91/255.0 blue:76/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:63/255.0 green:64/255.0 blue:56/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:58/255.0 green:62/255.0 blue:53/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:21/255.0 green:31/255.0 blue:27/255.0 alpha:1].CGColor];
gl.locations = @[@(0), @(0.1f), @(0.2f), @(0.3f), @(0.4f), @(0.6f), @(0.7f), @(0.8f), @(0.9f), @(1.0f)];
gl.cornerRadius = 15.f;