Search code examples
javaswingawtjava-2dgraphics2d

Coordinate transformation Dilemma, User coordinate to Device coordinate?


I am working on a task which includes data such as "length" of a road in "millimetre". And as per the specification my JFrame should be 4meter * 3meter ( How to convert this into device coordinate...?).

Now, I know at least that this data is real world data and not device's pixel data. However after finding out few sources you can actually transform these data into pixel by Graphics2D class.

Resource I found these information is in,

Core Java 2, Volume II - Advanced Feature, Author - Cay S. Horstmann & Gary Cornell

However, I googled for actual examples with no luck.

Does anyone know any source where I can read more about this. And if you have any examples where someone has actually did something like this, That would be more informative.

Research so far : So far I know that we need to give a assumptions to Graphics2D class of number of pixels in meters. In Graphics2D there is method which helps you to set this assumption. Method is ,

g2D.scale(pixelsPerMeter, pixelsPerMeter);
//And than I can draw a line with meter or millimetre coordinates
g2D.draw(new Line2D.Double(coordinates in meter));

I tried above code but really hard to draw line where I actually want to.

Any help of understanding will be very helpful.

Thanks


Solution

  • I find it easier to create an java.awt.geom.AffineTransform object and transform the coordinates from meters to pixels myself. In your case, use AffineTransform.getScaleInstance(sx, sy).

    Then I call Graphics2D functions to draw my lines and polygons using pixel coordinates.

    This makes debugging easier: you can see the coordinate values before and after the transformation.

    The Advanced Topics section in the Java Tutorial describes how to do transformations with Graphics2D, with examples: http://download.oracle.com/javase/tutorial/2d/index.html