Search code examples
javamathcoordinate

Converting a coordinate from one space to another


I seem to be having a bit of a math fail here... I need to convert an (x,y) point from one coordinate space to another - not in the sense of polar to cartesian or anything of the sort... just from one bound to another. i.e., for a particular (x,y) that falls in the rectangle with lower left (-100, -100) and upper right (100,100), I need to find out where that point would be in a rectangle with lower left (0,0) and upper right (500, 500).

I feel like this is just simple math but I'm having a heck of a time getting it right...

It is for a little computer graphics program written in java. Essentially there is a clip window that changes, and that clip window needs to fill the whole view window. Initial values for clip and view are given by the above rectangles, in that order. However, the clip could change to, for example, a rectangle with lower left (-80, -65) and upper right (75, 65). I would then need to convert a point that falls within that rectangle to a point that falls within the view window (lower left (0,0), upper right (500, 500))

Here is what I have for it right now:

public int normalizeX(float x) {
    float clipWidth = clipRight - clipLeft;
    int viewWidth = viewRight - viewLeft;
    x += 100; //Get x into range [0, 200] instead of [-100, 100]
    //First convert x to value within clip width, then "scale" to viewport width
    return (int)(((clipWidth*x)/200) * (viewWidth/clipWidth));
}

public int normalizeY(float y) {
    float clipHeight = clipTop - clipBottom;
    int viewHeight = viewTop - viewBottom;
    y += 100; //Get y into range [0, 200] instead of [-100, 100]
    //First convert y to value within clip height, then "scale" to viewport height
    return (int)(((clipHeight*y)/200) * (viewHeight/clipHeight));
}

Thanks for any help!


Solution

  • Assuming your old bounds are xLoOld and xHiOld (-80 and 75, respectively, in your example) and your new bounds are xLoNew and xHiNew (0 and 500, respectively, in your example), then you can normalize your xOld to your new coordinate system like this:

    xNew = (xOld-xLoOld) / (xHiOld-xLoOld) * (xHiNew-xLoNew) + xLoNew
    

    Same thing for y.