How to change size of thumb image of UISlider programmatically
Asked Answered
M

2

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?

Mercaptide answered 27/6, 2012 at 8:12 Comment(0)
S
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.

Strategy answered 27/6, 2012 at 8:16 Comment(2)
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.widthratio, penSize_sld.currentThumbImage.size.heightratio); UIImage *changeImage = [UIImage imageWithImage:penSize_sld.currentThumbImage scaledToSize:ss]; [penSize_sld setThumbImage:changeImage forState:UIControlStateNormal]; if (sender == penSize_sld) { brushWidth = penSize_sld.value; }Mercaptide
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]; ..... }Mercaptide
T
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
    }
}
Tolle answered 2/3, 2017 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.