Adrao
Adrao

Reputation: 510

Convert Cursor Coordinates

I have this code which converts the X coordinate of the mouse cursor in a float value:

    private float XToFloat(int x)
    {
        return (float)(x / (float)this.Width);
    }

the result is something like this 0.01234567 now how can i convert that back to the original coordinate? Can anyone help?

Upvotes: 0

Views: 145

Answers (3)

Snippet
Snippet

Reputation: 1560

Its just a simple mathematics. using the code.

private float XToFloat(int x)
{
   return (float)(x / (float)this.Width);
}

Example:

//If Width Value
this.Width = 10;

calling the function and passing a value to the parameter like XToFloat(5); the function will return a value of 0.5.

//inside the function
    (float)(x / (float)this.Width); => (float)(5 / (float)10);
//z = x/y

to convert that back to the original value we create a function we multiply the float value to the Width.

private int FloatToX(float f){
        return (int)((float)this.Width*f);
    }

Example is FloatToX(0.5) 0.5x10 will return an integer value of 5

//inside the function
    (int)((float)this.Width*f) => (int)((float)10*0.5)
//x = zy

in mathematics its just

to get z

z = x/y

to get x

x = zy

to get y

y = x/z

Upvotes: 2

Shrivallabh
Shrivallabh

Reputation: 2893

Let us say this.Width as Y now

Converted value(0.01234567) as Z

so what you are doing is

z=x/y 

what u want is x and u have Z this time so

Z*Y=X

Upvotes: 0

Martin Svanberg
Martin Svanberg

Reputation: 137

This is simple maths:

float floatValue = (float)(x / (float)this.Width);
int cursorX = floatValue * this.Width;

Edit: Think of the float value as a percentage. It ranges from 0 to 1, which is equivalent to 0-100%. The float version of the x coordinate is then simply a percentage of the width:

0%   width   100%
+-------------+
|             |
|        80%  |
|         X   |
|             |
+-------------+

So to get the original coordinate back you multiply the width by the percentage.

Upvotes: 0

Related Questions