如何避免多边形重叠 [英] How to avoid overlapping polygon

查看:237
本文介绍了如何避免多边形重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,当用户每次按下按钮时,都会自动绘制许多多边形。多边形的点是使用随机函数自动生成的。问题在于,由于多边形的点是随机生成的,因此某些多边形与其他多边形重叠。如何避免这种情况,使每个显示的多边形都不会重叠?

I created a program to draw many polygons automatically everytimes user presses a button. The points of the polygon are generated automatically using the random function. The problem is that, since the points of the polygon were randomly generated, some of the polygon are overlap with other polygon. How can I avoid this, so that every polygon shown without being overlapped?

.....
List<Polygon> triangles = new LinkedList<Polygon>(); 
Random generator = new Random();

public void paintComponent(Graphics g) {

   for(int i = 0; i < 10; i++) {
      double xWidth = generator.nextDouble() * 40.0 + 10.0;
      double yHeight = generator.nextDouble() * 40.0 + 10.0;

      xCoord[0] = generator.nextInt(MAX_WIDTH);
      yCoord[0] = generator.nextInt(MAX_HEIGHT); 

      xCoord[1] = (int) (xCoord[0] - xWidth);
      xCoord[2] = (int) (xCoord[1] + (xWidth/2));       

      yCoord[1] = yCoord[0];
      yCoord[2] = (int) (yCoord[1] - yHeight);     

      triangles.add( new Polygon(xCoord,yCoord, 3));          
   }

   Graphics2D g2 = (Graphics2D) g;
   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   g2.setStroke(new BasicStroke(1)); 
   g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.00f));
   g2.setPaint(Color.black);//set the polygon line 

   for (Polygon triangle : triangles)  g2.drawPolygon(triangle);

   Polygon[] triArray = triangles.toArray(new Polygon[triangles.size()]);
   for (Polygon p:triArray) triangles.remove (p);

}


推荐答案

创建区域新多边形以及所有现有多边形中的对象。
从现有多边形中减去新多边形的面积。如果减法改变了面积,则多边形重叠。

Create Area objects from your new polygon as well as for all existing polygons. Subtract the new polygon's area from the existing ones. If the subtract changed the area, the polygons overlap.

Area newArea = new Area(newPolygon);
Area existingArea = new Area(existingPolygon);
Area existingAreaSub = new Area(existingPolygon); existingAreaSub.subtract(newArea);
boolean intersects = existingAreaSub.equals(existingArea);

这篇关于如何避免多边形重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆