Search code examples
iosobjective-cuislider

Change Image for a Range in UISlider


Is there any way to change the Trackimage for a Range in UISlider, independent from the Position of the Thumb?

It should look like this:

Slider

I already have the Slider without the yellow Range. How can i achieve the yellow Range?


Solution

  • If your deployment target is at least iOS 6.0, you can do this using UIImageResizingModeTile. Example code:

    static UIImage *blueYellowStripesImage() {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 9), YES, 0); {
            [[UIColor blueColor] setFill];
            UIRectFill(CGRectMake(0, 0, 50, 9));
            [[UIColor yellowColor] setFill];
            UIRectFill(CGRectMake(50, 0, 50, 9));
            [[UIColor colorWithWhite:0 alpha:0.4] setFill];
            UIRectFillUsingBlendMode(CGRectMake(0, 5, 100, 4), kCGBlendModeNormal);
        }
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        image = [image resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile];
        return image;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UIImage *image = blueYellowStripesImage();
        [self.slider setMinimumTrackImage:image forState:UIControlStateNormal];
        [self.slider setMaximumTrackImage:image forState:UIControlStateNormal];
    }
    

    Result:

    slider with tiled image tracks