9

I would like to make the custom UISlider, something like this

|o----------| -> |-----O------| -> |------------〇|

the thumbImage will be small at the minimum value, it will increase the size during the slider value increase, otherwise it will decrease.

is anyone know how to do it?

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
AndyYeung
  • 105
  • 1
  • 1
  • 5

2 Answers2

11

You can use this code:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Taken from here.

The extra work you will have, will be a method A that will call the imageWithImage:scaledToSize: when the UISlider's value changes.

Community
  • 1
  • 1
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
  • thx for Reply , i have added with the follow, am i right? But i test with trouble image size occur... float ratio = penSize_sld.value/( penSize_sld.maximumValue/2); CGSize ss= CGSizeMake(penSize_sld.currentThumbImage.size.width*ratio, penSize_sld.currentThumbImage.size.height*ratio); UIImage *changeImage = [UIImage imageWithImage:penSize_sld.currentThumbImage scaledToSize:ss]; [penSize_sld setThumbImage:changeImage forState:UIControlStateNormal]; if (sender == penSize_sld) { brushWidth = penSize_sld.value; } – AndyYeung Jun 27 '12 at 08:57
  • That work! Thanks JackyBoy `float ratio = penSize_sld.value/( penSize_sld.maximumValue/2); if ( ratio < 0.8) { ratio = 0.8; } UIImage *thumbImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"drawview_dragbar_bu_1.png" ofType:nil]]; CGSize ss= CGSizeMake(thumbImage.size.width*ratio,thumbImage.size.height*ratio); UIImage *changeImage = [UIImage imageWithImage:thumbImage scaledToSize:ss]; [penSize_sld setThumbImage:changeImage forState:UIControlStateNormal]; ..... }` – AndyYeung Jun 27 '12 at 09:22
  • @Peres: Help me : https://stackoverflow.com/questions/52987375/ios-custom-slider-remove-min-and-max-space-from-both-ends – Abhishek Thapliyal Oct 25 '18 at 11:30
6

Swift 3:

extension UIImage {

    func scaleToSize(newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return newImage
    }
}
Teodor Ciuraru
  • 3,417
  • 1
  • 32
  • 39