4

一些Graphics2D方法,例如drawString,具有将坐标作为int或的版本float。是否有任何理由选择其中之一?

同样,我应该使用较新的Shape类,例如Rectangle2D(使用浮点坐标)还是使用Rectangle(将坐标定义为ints)?

4

1 回答 1

4

我看到 int 和 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.

如果您需要更高的精度,请使用 float,如果位置足够,请使用 int。

关于您的第二个问题,请参见下文描述/回答的以下内容,Rectangle 和 Rectangle2D Difference

矩形使用 int 坐标。Rectangle2D 是一个抽象类,它不关心您使用的是 int、double 还是 float 坐标。

如果您需要更高的双精度和浮点精度,则必须使用 Rectangle2D。

Rectangle2D 是基类,因此如果您正在编写以抽象方式对矩形进行操作的代码,请选择 Rectangle2D,并像这样分配它:

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

或者

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

如果您知道您只会处理整数,则可以一直使用 Rectangle。

您可能会说 Rectangle 应该称为 Rectangle2D.Integer。但这也不完全是,因为例如 Rectangle 是三个实现可序列化接口的唯一一个。

就像 skaffman 评论的那样,这是一个遗留问题。

于 2011-04-27T23:41:57.850 回答