代码实现- (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;}
链接:http://www.jianshu.com/p/be4d76e38e8c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。