Swing draws on incorrect coordinates
I am building a simulator to assist in a project I am working on with some guys at Uni. I am animating what is essentially a football pitch with two "players" (actually Lego robots).
The problem I am encountering is that the coordinates that I use for drawing seem to be wrong as everything is drawn further back (in the x and y) than what I intend. For instance to draw the white line on the far side of the pitch I do this:
double X_RATIO = this.getSize().width / 244;
double Y_RATIO = this.getSize().height / 122;
g.fillRect((int) (243 * X_RATIO), (int) (0 * Y_RATIO), (int) (1 * X_RATIO), (int) (122 * Y_RATIO));
You can see that I scale where it is drawn by the current size so I can always use the standard size of the pitch as my coordinate system (here it is 244 x 122). This line is drawn at least 10 pix开发者_JAVA技巧els back from the right side of the panel however (Also is up from the bottom around 5 pixels).
At first I thought it would to do with the casting but I leave this to the last possible second (only casting at the draw stage where positions must be int anyway). Does anyone have any idea what the problem might be? Needless to say it is very frustrating as I can't see what's wrong with my maths.
Check your ratios X_RATIO and Y_RATIO since you used integer division on the right hand side. You may replace it by
double X_RATIO = this.getSize().width / 244.0;
double Y_RATIO = this.getSize().height / 122.0;
to get correct scaling behaviour.
I think it's due to the way ratios are initialized : you do an int division, so the result is an int, not a double. cast one of the values as double to get a double result.
精彩评论