UISlider底部滑动条颜色渐变

动画展示

在上篇博文中 使用CAGradientLayer实现背景颜色渐变和特效 有朋友问UISlider底部滑动条怎么弄渐变色。刚写了个Demo,由于回复区贴代码不好看所以专门放上博客中一起看看吧。

代码实现

- (void)viewDidLoad {
    [super viewDidLoad];
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(100, 100, 200, 55)];
    [self.view addSubview:self.slider];
    
    UIColor *startColor = [UIColor colorWithRed:190.0/255 green:253.0/255 blue:255.0/255 alpha:1.0];
    UIColor *endColor = [UIColor colorWithRed:0.0/255 green:222.0/255 blue:255.0/255 alpha:1.0];
    NSArray *colors = @[startColor,endColor];
    UIImage *img = [self getGradientImageWithColors:colors imgSize:self.slider.bounds.size];
    [self.slider setMinimumTrackImage:img forState:UIControlStateNormal];
    
    
}

-(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 | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容