How to get the center of the thumb image of UISlider

willc2 picture willc2 · Nov 11, 2009 · Viewed 27.6k times · Source

I'm creating a custom UISlider to test out some interface ideas. Mostly based around making the thumb image larger.

I found out how to do that, like so:

UIImage *thumb = [UIImage imageNamed:@"newThumbImage_64px.png"];  
[self.slider setThumbImage:thumb forState:UIControlStateNormal];  
[self.slider setThumbImage:thumb forState:UIControlStateHighlighted];  
[thumb release];  

To calculate a related value I need to know where the center point of the thumb image falls when it's being manipulated. And the point should be in it's superview's coordinates.

Looking at the UISlider docs, I didn't see any property that tracked this.

Is there some easy way to calculate this or can it be derived from some existing value(s)?

Answer

willc2 picture willc2 · Nov 26, 2009

This will return the correct X position of center of thumb image of UISlider in view coordinates:

- (float)xPositionFromSliderValue:(UISlider *)aSlider {
     float sliderRange = aSlider.frame.size.width - aSlider.currentThumbImage.size.width;
     float sliderOrigin = aSlider.frame.origin.x + (aSlider.currentThumbImage.size.width / 2.0);

     float sliderValueToPixels = (((aSlider.value - aSlider.minimumValue)/(aSlider.maximumValue - aSlider.minimumValue)) * sliderRange) + sliderOrigin;

     return sliderValueToPixels;
}

Put it in your view controller and use it like this: (assumes property named slider)

float x = [self xPositionFromSliderValue:self.slider];