S.Podder
S.Podder

Reputation: 35

Print coordinates of convex polygons which are inside of another convex polygon in java

I am drawing four polygons. I need to determine coordinates of points which are inside of other polygon. i have searched in google but not getting proper code for that. Please suggest an approach or post some code with my set of coordinates here.

// Draw and fill polygons
import java.awt.Graphics;

public class Polygon2 extends java.applet.Applet
{
 int xCoords[] = { 10,90,200,270,200,90};
 int yCoords[] = { 50,20,20,50,130,130};
 //int xFillCoords[] = { 450, 600, 700, 550, 450, 450 };

 int x2Coords[] = { 120,230,200,150,100};
 int y2Coords[] = { 10,10,60,80,70};


 public void paint(Graphics g)
 {
  g.drawPolygon(xCoords, yCoords, 6);
  g.drawPolygon(x2Coords, y2Coords, 5);
  g.drawRect(60, 60, 30, 30);
  g.drawRect(100, 150, 150, 100); 
  //g.fillPolygon(xFillCoords, yCoords, 5);
 }
}

four polygons

Upvotes: 1

Views: 230

Answers (1)

kaya3
kaya3

Reputation: 51162

The problem of testing whether a point is in a polygon has several standard algorithms: these two are probably the simplest to understand.

  • The ray-casting algorithm - cast a "ray" out from the point, and count how many edges of the polygon the ray crosses. The point is in the polygon if and only if it crosses an odd number of edges.
  • The winding number algorithm - compute the number of times the polygon "winds" 360 degrees around the point. The point is in the polygon if and only if the winding number is non-zero.

Both algorithms work for non-convex polygons, too. Unless this is a learning exercise, then I would recommend finding an existing implementation of one of these algorithms rather than writing your own.

Upvotes: 2

Related Questions