1. 程式人生 > >UISlider——漸變色滑動條

UISlider——漸變色滑動條

漸變色的滑動條效果網上實現方案有很多,方法都大同小異,就是用顏色組生成新的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生成漸變色Layer

使用上面提到的辦法雖然可以生成漸變色,但要做到下圖這樣的效果卻有些問題,在滑動的時候無法保證圖片保持不動。

圖片中漸變色滑動條的設定非常簡單,直接使用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;