使用addRectangle将矩形转换为多边形

时间:2015-11-27 13:09:38

标签: java polygon rectangles

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

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; 
} 

1 个答案:

答案 0 :(得分: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