android滑动 ui渐变,UISlider底部滑动条颜色渐变

  • Post author:
  • Post category:其他


动画展示

be4d76e38e8c

在上篇博文中 使用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;

}