Java Code Examples for java.awt.Polygon#contains()

The following examples show how to use java.awt.Polygon#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PolygonGrabber.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
private boolean doesPolygonContainAnyBlackInside(
    final Polygon poly, final BufferedImage imageCopy, final Graphics imageCopyGraphics) {
  // we would like to just test if each point is both black and contained within the polygon,
  // but contains counts
  // the borders, so we have to turn the border edges a different color (then later back to
  // black again) using a
  // copy of the image
  imageCopyGraphics.setColor(Color.GREEN);
  imageCopyGraphics.drawPolygon(poly.xpoints, poly.ypoints, poly.npoints);
  final Rectangle rect = poly.getBounds();
  for (int x = rect.x; x < rect.x + rect.width; x++) {
    for (int y = rect.y; y < rect.y + rect.height; y++) {
      if (isBlack(x, y, imageCopy) && poly.contains(new Point(x, y))) {
        imageCopyGraphics.setColor(Color.BLACK);
        imageCopyGraphics.drawPolygon(poly.xpoints, poly.ypoints, poly.npoints);
        return true;
      }
    }
  }
  imageCopyGraphics.setColor(Color.BLACK);
  imageCopyGraphics.drawPolygon(poly.xpoints, poly.ypoints, poly.npoints);
  return false;
}
 
Example 2
Source File: TZWorld.java    From geosense with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if a (lat,lon) point is contained in this extent
 */
public boolean contains(double lat, double lon) {
	int ilat = integerize(lat);
	int ilon = integerize(lon);
	if (!bbox.contains(ilon, ilat))
		return false;

	if (excludes != null)
		for (Polygon exclude : excludes)
			if (exclude.contains(ilon, ilat))
				return false;

	if (includes != null)
		for (Polygon include : includes)
			if (include.contains(ilon, ilat))
				return true;

	return false;
}
 
Example 3
Source File: Util.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Finds a land territory name or some sea zone name where the point is contained in according to
 * the territory name -> polygons map. If no land or sea territory has been found a default name
 * is returned.
 *
 * @param p A point on the map.
 * @param terrPolygons a map territory name -> polygons
 * @param defaultTerrName Default territory name that gets returns if nothing was found.
 * @return found territory name of defaultTerrName
 */
public static String findTerritoryName(
    final Point p, final Map<String, List<Polygon>> terrPolygons, final String defaultTerrName) {
  String lastWaterTerrName = defaultTerrName;
  // try to find a land territory.
  // sea zones often surround a land territory
  for (final String terrName : terrPolygons.keySet()) {
    final Collection<Polygon> polygons = terrPolygons.get(terrName);
    for (final Polygon poly : polygons) {
      if (poly.contains(p)) {
        if (Util.isTerritoryNameIndicatingWater(terrName)) {
          lastWaterTerrName = terrName;
        } else {
          return terrName;
        }
      } // if p is contained
    } // polygons collection loop
  } // terrPolygons map loop
  return lastWaterTerrName;
}
 
Example 4
Source File: MapData.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/** Get the territory at the x,y co-ordinates could be null. */
public String getTerritoryAt(final double x, final double y) {
  String seaName = null;
  // try to find a land territory.
  // sea zones often surround a land territory
  for (final String name : polys.keySet()) {
    final Collection<Polygon> polygons = polys.get(name);
    for (final Polygon poly : polygons) {
      if (poly.contains(x, y)) {
        if (Util.isTerritoryNameIndicatingWater(name)) {
          seaName = name;
        } else {
          return name;
        }
      }
    }
  }
  return seaName;
}
 
Example 5
Source File: TerritoryOverLayDrawable.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void draw(
    final Rectangle bounds,
    final GameData data,
    final Graphics2D graphics,
    final MapData mapData) {
  final Territory territory = data.getMap().getTerritory(territoryName);
  final List<Polygon> polygons = mapData.getPolygons(territory);
  graphics.setColor(color);
  for (final Polygon polygon : polygons) {
    if (!polygon.intersects(bounds) && !polygon.contains(bounds)) {
      continue;
    }

    final Polygon translatedPolygon = Util.translatePolygon(polygon, -bounds.x, -bounds.y);
    if (operation == Operation.FILL) {
      graphics.fillPolygon(translatedPolygon);
    } else {
      graphics.drawPolygon(translatedPolygon);
    }
  }
}
 
Example 6
Source File: TerritoryDrawable.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
protected static void draw(
    final Rectangle bounds,
    final Graphics2D graphics,
    final MapData mapData,
    final Territory territory,
    final Paint territoryPaint) {
  final List<Polygon> polygons = mapData.getPolygons(territory);
  for (final Polygon polygon : polygons) {
    if (!polygon.intersects(bounds) && !polygon.contains(bounds)) {
      continue;
    }

    final Polygon translatedPolygon = Util.translatePolygon(polygon, -bounds.x, -bounds.y);
    graphics.setPaint(territoryPaint);
    graphics.fillPolygon(translatedPolygon);
    graphics.setColor(Color.BLACK);
    graphics.drawPolygon(translatedPolygon);
  }
}
 
Example 7
Source File: SeaZoneOutlineDrawable.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void draw(
    final Rectangle bounds,
    final GameData data,
    final Graphics2D graphics,
    final MapData mapData) {
  final Territory territory = data.getMap().getTerritory(territoryName);
  final List<Polygon> polys = mapData.getPolygons(territory);
  graphics.setColor(Color.BLACK);
  for (final Polygon polygon : polys) {
    if (!polygon.intersects(bounds) && !polygon.contains(bounds)) {
      continue;
    }

    graphics.drawPolygon(Util.translatePolygon(polygon, -bounds.x, -bounds.y));
  }
}
 
Example 8
Source File: MapTools.java    From addrparser with Apache License 2.0 5 votes vote down vote up
/**
 * To determine whether a point in a polygon
 * @param p        The point to determine
 * @param area     Polygon 
 * @return  true, point in polygon, otherwise false.
 */
public static boolean inPolygonArea(Point p, Point area[])
{
	Polygon pol = new Polygon();
	for ( int i = 0; i < area.length; i++ )
	{
		pol.addPoint( (int) (area[i].getLon() * 100000), (int) (area[i].getLat() * 100000) );
	}
	return pol.contains( (int) (p.getLon() * 100000), (int) (p.getLat() * 100000) );
}
 
Example 9
Source File: Glyphs.java    From libreveris with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Look up in a collection of glyphs for <b>all</b> glyphs
 * contained in a provided polygon.
 *
 * @param collection the collection of glyphs to be browsed
 * @param polygon    the containing polygon
 * @return the glyphs found, which may be an empty list
 */
public static Set<Glyph> lookupGlyphs (
        Collection<? extends Glyph> collection,
        Polygon polygon)
{
    Set<Glyph> set = new LinkedHashSet<>();

    for (Glyph glyph : collection) {
        if (polygon.contains(glyph.getBounds())) {
            set.add(glyph);
        }
    }

    return set;
}
 
Example 10
Source File: PicMap.java    From megamek with GNU General Public License v2.0 5 votes vote down vote up
private boolean intersects(Shape sh, int x, int y) {
    if (sh instanceof Rectangle) {
        Rectangle r = (Rectangle) sh;
        return r.contains(x, y);
    } else if (sh instanceof Polygon) {
        Polygon p = (Polygon) sh;
        return p.contains(x, y);
    }
    return false;
}
 
Example 11
Source File: Profile.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/**Check if the given point (usually from a MOUSE_PRESSED MouseEvent) is contained within the boundaries of this object. The point is expected as local coordinates. */
public boolean containsPoint(final int x_p, final int y_p) {
	// as in getPerimeter():
	final int n_i = p_i[0].length;
	final int[] intx = new int[n_i];
	final int[] inty = new int[n_i];
	for (int i=0; i<n_i; i++) {
		intx[i] = (int)p_i[0][i];
		inty[i] = (int)p_i[1][i];
	}
	final Polygon polygon = new Polygon(intx, inty, n_i);
	return polygon.contains(x_p, y_p);
}
 
Example 12
Source File: PolygonGrabber.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** returns false if there is no points in a current polygon. returns true if there is. */
private boolean pointInCurrentPolygon(final Point p) {
  if (current == null) {
    return false;
  }
  for (final Polygon item : current) {
    if (item.contains(p)) {
      return true;
    }
  }
  return false;
}
 
Example 13
Source File: TerritoryNameDrawable.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static boolean isRectangleContainedInTerritory(
    final Rectangle rectangle, final Territory territory, final MapData mapData) {
  final List<Polygon> polygons = mapData.getPolygons(territory.getName());
  for (final Polygon polygon : polygons) {
    if (polygon.contains(rectangle)) {
      return true;
    }
  }
  return false;
}
 
Example 14
Source File: IslandTerritoryFinder.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/** Checks that a given land territory would be contained by a given sea territory. */
private Predicate<String> landIsContainedBySeaTerritory(
    final String seaTerritory, final Map<String, List<Polygon>> polygons) {

  // Function where given a territory name, give us a polygon for that territory
  final Function<String, Polygon> polygonLookup =
      territoryName -> polygons.get(territoryName).iterator().next();

  return land -> {
    final Polygon seaPoly = polygonLookup.apply(seaTerritory);
    final Polygon landPoly = polygonLookup.apply(land);
    return seaPoly.contains(landPoly.getBounds());
  };
}
 
Example 15
Source File: Glyphs.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Look up in a collection of glyph instances for <b>all</b> glyph
 * instances contained in a provided polygon.
 *
 * @param collection the collection of glyph instances to be browsed
 * @param polygon    the containing polygon
 * @return the glyph instances found, which may be an empty list
 */
public static Set<Glyph> containedGlyphs (Collection<? extends Glyph> collection,
                                          Polygon polygon)
{
    Set<Glyph> set = new LinkedHashSet<>();

    for (Glyph glyph : collection) {
        if (polygon.contains(glyph.getBounds())) {
            set.add(glyph);
        }
    }

    return set;
}
 
Example 16
Source File: Geometry.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int percent(float x1,float y1, float width, float height,Polygon p){
	int counter=0;
	double dx=width/10;
	double dy=height/10;
	for(int i=0;i<10;i++)
		for(int j=0;j<10;j++){
			if(p.contains(dx*i+x1,dy*j+y1))counter++;
		}
	return counter;
}
 
Example 17
Source File: DevToolsOverlay.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
private void renderTileTooltip(Graphics2D graphics, Tile tile)
{
	Polygon poly = Perspective.getCanvasTilePoly(client, tile.getLocalLocation());
	if (poly != null && poly.contains(client.getMouseCanvasPosition().getX(), client.getMouseCanvasPosition().getY()))
	{
		toolTipManager.add(new Tooltip("World Location: " + tile.getWorldLocation().getX() + ", " + tile.getWorldLocation().getY() + ", " + client.getPlane()));
		OverlayUtil.renderPolygon(graphics, poly, GREEN);
	}
}
 
Example 18
Source File: FindPointInPolygonOccurrence.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
private boolean isInside(String point, String polygon) {
    Point p = parsePoint(point);
    Polygon pol = parsePolygon(polygon);
    if(p == null || pol == null) return false;
    return pol.contains(p);
}
 
Example 19
Source File: clsUtility.java    From mil-sym-java with Apache License 2.0 4 votes vote down vote up
/**
 * construct a line segment outside the polygon corresponding to some index
 * @param tg
 * @param index
 * @param dist
 * @return 
 */
protected static Line2D getExtendedLine(TGLight tg,
        int index,
        double dist)
{
    Line2D line=null;
    try
    {
        Polygon polygon=new Polygon();
        int j=0;
        for(j=0;j<tg.Pixels.size();j++)
        {
            polygon.addPoint((int)tg.Pixels.get(j).x, (int)tg.Pixels.get(j).y);
        }
        POINT2 pt0=null; 
        POINT2 pt1=null; 
        if(tg.Pixels.size()>3)
        {
            pt0=tg.Pixels.get(index);
            pt1=tg.Pixels.get(index+1);
        }
        else
        {
            pt0=tg.Pixels.get(1);
            pt1=tg.Pixels.get(2);                
        }
        
        POINT2 ptExtend=null;
        int extend=-1;
        POINT2 midPt=lineutility.MidPointDouble(pt0, pt1,0);
        double slope=Math.abs(pt1.y-pt0.y)/(pt1.x-pt0.x);
        if(slope<=1)
        {
            ptExtend=lineutility.ExtendDirectedLine(pt0, pt1, midPt, lineutility.extend_above, 2);
            if(polygon.contains(ptExtend.x,ptExtend.y))
                extend=lineutility.extend_below;
            else
                extend=lineutility.extend_above;
        }
        else
        {
            ptExtend=lineutility.ExtendDirectedLine(pt0, pt1, midPt, lineutility.extend_left, 2);
            if(polygon.contains(ptExtend.x,ptExtend.y))
                extend=lineutility.extend_right;
            else
                extend=lineutility.extend_left;
            
        }
        POINT2 pt3=null;
        POINT2 pt4=null;
        pt3=lineutility.ExtendDirectedLine(pt0, pt1, pt0, extend, dist);
        pt4=lineutility.ExtendDirectedLine(pt0, pt1, pt1, extend, dist);
        line=new Line2D.Double(pt3.x, pt3.y, pt4.x, pt4.y);
    }
    catch (Exception exc) {            
        ErrorLogger.LogException(_className, "getExtendedLine",
                new RendererException("Failed inside getExtendedLine", exc));
    }
    return line;
}
 
Example 20
Source File: clsUtilityGE.java    From mil-sym-java with Apache License 2.0 4 votes vote down vote up
/**
 * tests of a Line2D intersects a polygon by using line.intersectsLine on each segment of the polygon
 * assumes clip clipping area was parsed to shift points of vertical segments to make them not vertical
 * @param line a clipping line in the clipping polygon
 * @param clipPts array of clip points assumed to be closed
 * @return true if the line intersects the clip bounds
 */
private static boolean lineIntersectsClipArea(Line2D line, 
        ArrayList<Point2D> clipPts)
{
    boolean result=false;
    try
    {
        int j=0;           
        
        //test if polygon contains an end point
        Polygon poly=new Polygon();
        for(j=0;j<clipPts.size();j++)            
            poly.addPoint((int)clipPts.get(j).getX(),(int)clipPts.get(j).getY());
        
        if(poly.contains(line.getX1(),line.getY1()))
            return true;
        if(poly.contains(line.getX2(),line.getY2()))
            return true;
        //end section
        
        Line2D currentSegment=null;
        for(j=0;j<clipPts.size()-1;j++)
        {
            currentSegment=new Line2D.Double(clipPts.get(j).getX(),clipPts.get(j).getY(),clipPts.get(j+1).getX(),clipPts.get(j+1).getY());
            if(line.intersectsLine(currentSegment)==true)
                return true;            
        }
        //if the clipPts are not closed then the above loop did not test the closing segment            
        Point2D pt0=clipPts.get(0);
        Point2D ptLast=clipPts.get(clipPts.size()-1);
        //int n=clipPts.size()-1;            
        if(pt0.getX()!=ptLast.getX() || pt0.getY()!=ptLast.getY())
        {
            //currentSegment=new Line2D.Double(clipPts.get(n).getX(),clipPts.get(n).getY(),clipPts.get(0).getX(),clipPts.get(0).getY());
            currentSegment=new Line2D.Double(ptLast.getX(),ptLast.getY(),pt0.getX(),pt0.getY());
            if(line.intersectsLine(currentSegment)==true)
                return true;                            
        }
    }
    catch (Exception exc) {
        ErrorLogger.LogException(_className, "lineIntersectsClipArea",
                new RendererException("Failed inside lineIntersectsClipArea", exc));
    }
    return result;
}