1
\$\begingroup\$

Currently, I have a JFrame for my game to render in, and I'm using Graphics2D for drawing (The games graphics are fairly simple 2D sprites). However, my delta variable is a double, and all of the Graphics 2D methods (And Grpahics) use int. I tried to type cast the delta to an int, but it just rounds down to 0. So my question is, how can I render graphics using Graphics2D in Java with coordinates that are doubles. Can I convert it to work with Graphics2D if there is no built in way? Or, is there a graphics library that can support doubles for coordinates?

\$\endgroup\$
  • \$\begingroup\$ How do you intend to light a fraction of a pixel on your computer monitor? \$\endgroup\$ – ClassicThunder Dec 6 '12 at 4:25
  • 2
    \$\begingroup\$ It can be done with sub-pixel accurate rendering and antialiasing. \$\endgroup\$ – msell Dec 6 '12 at 8:06
2
\$\begingroup\$

Graphics class uses integer coordinates for all operations, but Graphics2D provides API with float and double accuracy. You can use Graphics2D.draw(Shape) and Graphics2D.fill(Shape) to get sub-pixel accuracy in rendering. You should also probably enable antialiasing for the Graphics2D object.

public void paintComponent(Graphics graphics) {
    Graphics2D g = (Graphics2D)graphics;
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.draw(new Line2D.Double(10.5, 10.5, 20.5, 20.5));
}

Alternatively you can scale, rotate and translate Graphics2D object or manipulate the AffineTransform directly. This might be needed if you want to draw images to double coordinates.

\$\endgroup\$
  • \$\begingroup\$ I was actually thinking about checking out Shape & using that. Thanks the for the answer! \$\endgroup\$ – thedeadlybutter Dec 6 '12 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.