【问题标题】:Convert rectangle to polygon with addRectangle使用 addRectangle 将矩形转换为多边形
【发布时间】:2015-11-27 13:09:37
【问题描述】:

如何使用以下方法将矩形转换为多边形?

public void addRectangle(int xPos, int yPos, int dX, int dY) 

我已经试过了:

/** * Converts the rectangle supplied into a polygon by making a new polygon 
and adding each of the rectangle's corners as points. */

public static Polygon RectangleToPolygon(Rectangle rect) {
   Polygon result = new Polygon(); 
   result.addPoint(rect.x, rect.y); 
   result.addPoint(rect.x + rect.width, rect.y); 
   result.addPoint(rect.x + rect.width, rect.y + rect.height); 
   result.addPoint(rect.x, rect.y + rect.height);
   return result; 
} 

【问题讨论】:

  • 你能用 Area 代替 Polygon 吗?用 Area 做这件事很容易
  • addRectangle 方法来自哪里?你有它还是你应该写它?当您尝试代码时发生了什么?出了什么问题?
  • 我应该写它。使用此方法将矩形转换为多边形并将其添加到数组列表中

标签: java polygon rectangles


【解决方案1】:

最好对所有数据使用构造函数。

public static Polygon RectangleToPolygon(Rectangle rect) {
    int[] xpoints = {rect.x, rect.x + rect.width, rect.x + rect.width, rect.x}:
    int[] ypoints = {rect.y, rect.y, rect.y + rect.height, rect.y + rect.height};
    return new Polygon(xpoints, ypoints, 4); 
}

或者用 rect 的 x、y、widht、height 替换

int xPos, int yPos, int dX, int dY

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多