Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the center of the thumb image of UISlider

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)?

like image 754
willc2 Avatar asked Nov 11 '09 10:11

willc2


2 Answers

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]; 
like image 98
willc2 Avatar answered Sep 29 '22 18:09

willc2


I tried this after reading the above suggestion -

yourLabel = [[UILabel alloc]initWithFrame:....];  //Call this method on Slider value change event  -(void)sliderValueChanged{     CGRect trackRect = [self.slider trackRectForBounds:self.slider.bounds];     CGRect thumbRect = [self.slider thumbRectForBounds:self.slider.bounds                                trackRect:trackRect                                    value:self.slider.value];      yourLabel.center = CGPointMake(thumbRect.origin.x + self.slider.frame.origin.x,  self.slider.frame.origin.y - 20); } 

For Swift version

func sliderValueChanged() -> Void {         let trackRect =  self.slider.trackRect(forBounds: self.slider.bounds)         let thumbRect = self.slider.thumbRect(forBounds: self.slider.bounds, trackRect: trackRect, value: self.slider.value)         yourLabel.center = CGPoint(x: thumbRect.origin.x + self.slider.frame.origin.x + 30, y: self.slider.frame.origin.y - 60)     } 

I could get most accurate value by using this snippet.

like image 25
girish_vr Avatar answered Sep 29 '22 17:09

girish_vr