Graphics2D: Should I use the int or float versions?

我们两清 提交于 2019-12-23 12:41:59

问题


Some of the Graphics2D methods, such as drawString, have versions that take coordinates as int or float. Are there any reasons to choose one over the other?

Likewise, should I use the newer Shape classes, such as Rectangle2D (which use floating-point coordinates), or use Rectangle (which defines coordinates as ints)?


回答1:


I see int and float -

drawString(AttributedCharacterIterator iterator, float x, float y) 
Renders the text of the specified iterator, using the Graphics2D context's current Paint.

drawString(AttributedCharacterIterator iterator, int x, int y) 
Renders the text of the specified iterator, using the Graphics2D context's current Paint.

Use float if you need more precision, int if the positions suffice.

Regarding your second question please see below which was described/answered by the following, Rectangle and Rectangle2D Difference:

Rectangle uses int coordinates. Rectangle2D is an abstract class that doesn't care if you're using int, double or float coordinates.

If you need the greater precision of double and float, you'll have to go with Rectangle2D.

Rectangle2D is the base class, so if you're writing code that operates on rectangular shapes in an abstract way, go for Rectangle2D, and assign it like so:

Rectangle2D rect = new Rectangle2D.Double(double, double, double, double);

or

Rectangle2D rect = new Rectangle(int, int, int, int)

If you know you're only going to deal with ints, you can use Rectangle all the way.

You might say that Rectangle should be called Rectangle2D.Integer. But that's not quite it either, because e.g. Rectangle is the only one of the three that implements the serializable interface.

Like skaffman commented, it's a bit of a legacy issue.



来源:https://stackoverflow.com/questions/5811928/graphics2d-should-i-use-the-int-or-float-versions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!