【问题标题】:Is it possible to turn a shape into a polygon in java?是否可以在java中将形状变成多边形?
【发布时间】:2023-03-12 22:13:01
【问题描述】:

我正在尝试将形状变成多边形。我的代码看起来像这样:

类 MyGraphicMethods 扩展了 Graphics
{
...
...
public void fillShape(Shape S)
{
g.fillPolygon((多边形)S);
}

当我跑步时

public static void main(String[] args) {
形状 S=new Rectangle(new Dimension(10, 100));
多边形 P=(多边形)S;
}

我得到一个 ClassCastException。 有人可以帮帮我吗?

【问题讨论】:

  • 多边形是否扩展了形状?如果是这样,矩形也扩展了形状。即使在现实中,您也无法将 Rectangle 转换为 Polygon, Rectangle 是四个边 Polygon。您需要根据结构的外观将 Rectangle 转换为 Polygon。希望对您有所帮助。
  • 抱歉,问题解决了——我找到了解决办法!
  • 不错。请回答您自己的问题以分享给其他人。谢谢

标签: java graphics geometry


【解决方案1】:

使用

extends Graphics2D

Graphics2D g = (Graphics2D) graphics;
g.fill(shape); // Or possibly fill(shape);

在 java 的历史中,Graphics 曾被 Graphics2D 扩展,为了向后兼容,Graphics 保留在 API 中。然而,总是可以将 Graphics 转换为 Graphics2D。

因此,扩展 Graphics 和 Graphics2D 都不是一个好主意。 这其实是我第一次看到。

【讨论】:

    【解决方案2】:

    你不能不明确地将你的形状转换回来,但你可以使用路径迭代器从形状重新创建它

    Poligon p = ....
    Shape s = p;
    
    PathIterator iter = s.pathIterator();
    

    我不想解释整个路径迭代器的东西,它已经被解释过 int Using PathIterator to return all line segments that constrain an Area?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多