Search code examples
algorithmmathsliderformulauislider

Formula for output value given a restricted range of input - Slider UI


Given these parameters:

minX = 10.0
maxX = 200.0
minY = 300
maxY = 700

The user can move x between minX and maxX. Find y so that it is the same proportionally between minY and maxY as x is between minX and maxX. So if x = 10, y = 300. If x = 200, y = 700.

Although x is a float, y must be an int.

What would this formula look like?

I've tried the below, but it works in an inverse fashion.

y = minY + (double)(maxX - x) / maxX * (maxY - minY)

Solution

  • This should work:

    ((x - minX) / (double)(maxX - minX)) * (maxY - minY) + minY
    

    ((x - minX) / (double)(maxX - minX)) computes the "percentage" of x in x's range. Then you simply multiply by the magnitude ((maxY - minY)) of the y range and add the lower bound to get y