Calculating the scroll position

I'm trying to draw a vertical scrollbar for my G15 applet, but I'm having problems positioning correctly (if you haven't done anything for the G15 LCD, think of it as a 160x43 pixel image).

This is my current code for positioning:

perc = (float)Math.Round( range / Items.Count+1 );

y = ( perc * SelectedID+1 );

      

The top of the scroll bar is 5 pixels from the top, and the bottom is 32 pixels. Y in this case will be the top end of the scrollbar, and I am using a length of 2 pixels; I tried to implement a variable length panel, it was as good as the code above. ID selection is based on 0.

All I need is math to figure out the position, no code needed to draw it.

Thank.

+2


source to share


1 answer


So you're just after some simple linear interpolation, right?

How do you have a value c

in a range a..b

and need to get the resulting value in a range x..y

based on its linear position between a

and b

?

The equation for this situation (assuming the numbers in question are floats or twins):

// c is between a and b
pos = (c-a)/(b-a) // pos is between 0 and 1
result = pos * (y-x) + x // result is between x and y

      

Now if everything is 0-indexed you can omit a

and x

to get



pos = c/b
result = pos * y

      

If any of the numbers you are working with are integer types, you will need to double them or float (or any real type of number) before divisions.

You can concatenate all the equations together if you can't pair something, but:

result = (c * y) / b

      

This ensures that c

both y

are multiplied together before integer division occurs, which will reduce the error associated with integer division.

+5


source







All Articles