tags:

views:

98

answers:

1

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

This is my current code for positioning:

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

y = ( perc * SelectedID+1 );

The upper edge of the scrollbar is at 5px from the top, the bottom edge is at 32px. Y in this case would be the upper end of the scrollbar, and I'm using a length of 2 pixels; I did try to impliment a variable length bar, it went about as well as the code above. SelectionID is 0 based.

All I need is the math to figure out the position, no need for code for drawing it.

Thanks.

+4  A: 

So you're just after straightforward linear interpolation, right?

As in you have a value c in the range a..b and you need a resulting value in the range x..y based on its linear position between a and b?

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

// 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're working with are integer types, you'll need to cast them to doubles or floats (or any real number type) before the divisions.

You can combine all of the equations together if you can't cast anything to doubles, though:

result = (c * y) / b

This will guarantee that c and y are multiplied together before the integer division takes place, which will reduce the error associated with integer division.

Welbog
Thanks, that got me close to where I needed to be. I actually needed (c * y) / (b - 1) for it to behave in the same way a scrollbar does.
Measter