Java Code Examples for java.awt.geom.Area#intersect()

The following examples show how to use java.awt.geom.Area#intersect() . 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: Utils.java    From jclic with GNU General Public License v2.0 6 votes vote down vote up
public static void tileImage(Graphics g, Image img, Rectangle dest, Rectangle source, ImageObserver io) {
  if (g.getClip().intersects(dest)) {
    int x, y;
    Area saveClip = new Area(g.getClip());
    Area newClip = new Area(saveClip);
    newClip.intersect(new Area(dest));
    g.setClip(newClip);
    Rectangle floatDest = new Rectangle(dest.x, dest.y, source.width, source.height);
    for (y = 0; y < dest.height; y += source.height) {
      for (x = 0; x < dest.width; x += source.width) {
        floatDest.setLocation(dest.x + x, dest.y + y);
        drawImage(g, img, floatDest, source, io);
      }
    }
    g.setClip(saveClip);
  }
}
 
Example 2
Source File: M.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Parts of @param a not intersected by any of @param vdt rois will be left untouched if @param remove_outside is false. */
static final public void apply(final VectorDataTransform vdt, final Area a, final boolean remove_outside) {
	final Area b = new Area();
	for (final VectorDataTransform.ROITransform rt : vdt.transforms) {
		// Cut the intersecting part from a:
		final Area intersection = new Area(a);
		intersection.intersect(rt.roi);
		a.subtract(intersection);
		// .. and add it to b, transformed:
		b.add(M.transform(rt.ct, intersection));
	}

	if (!M.isEmpty(a)) {
		if (remove_outside) {
			// Clear areas not affected any ROITransform
			Utils.log("WARNING: parts of an area in layer " + vdt.layer + "\n    did not intersect any transformation target\n    and where removed.");
			a.reset();
		} else Utils.log("WARNING: parts of an area in layer " + vdt.layer + "\n    remain untransformed.");
	}

	// Add b (the transformed parts) to what remains of a
	a.add(b);
}
 
Example 3
Source File: FXGraphics2D.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns {@code true} if the rectangle (in device space) intersects
 * with the shape (the interior, if {@code onStroke} is false, 
 * otherwise the stroked outline of the shape).
 * 
 * @param rect  a rectangle (in device space).
 * @param s the shape.
 * @param onStroke  test the stroked outline only?
 * 
 * @return A boolean. 
 */
@Override
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
    Shape ts;
    if (onStroke) {
        ts = this.transform.createTransformedShape(
                this.stroke.createStrokedShape(s));
    } else {
        ts = this.transform.createTransformedShape(s);
    }
    if (!rect.getBounds2D().intersects(ts.getBounds2D())) {
        return false;
    }
    Area a1 = new Area(rect);
    Area a2 = new Area(ts);
    a1.intersect(a2);
    return !a1.isEmpty();
}
 
Example 4
Source File: AreaList.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Subtracts the given ROI, and then creates a new AreaList with identical properties and the content of the subtracted part. Returns null if there is no intersection between sroi and the Area for layer_id. */
public AreaList part(final long layer_id, final ShapeRoi sroi) throws NoninvertibleTransformException {
	// The Area to subtract, in world coordinates:
	final Area sub = M.getArea(sroi);
	// The area to subtract from:
	final Area a = getArea(layer_id);
	if (null == a || M.isEmpty(a)) return null;
	// The intersection:
	final Area inter = a.createTransformedArea(this.at);
	inter.intersect(sub);
	if (M.isEmpty(inter)) return null;

	// Subtract from this:
	this.subtract(layer_id, sroi);

	// Create new AreaList with the intersection area, and add it to the same LayerSet as this:
	final AreaList ali = new AreaList(this.project, this.title, 0, 0);
	ali.color = new Color(color.getRed(), color.getGreen(), color.getBlue());
	ali.visible = this.visible;
	ali.alpha = this.alpha;
	ali.addArea(layer_id, inter);
	this.layer_set.add(ali); // needed to call updateBucket
	ali.calculateBoundingBox(null != layer_set ? layer_set.getLayer(layer_id) : null);

	return ali;
}
 
Example 5
Source File: FXGraphics2D.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Clips to the intersection of the current clipping region and the
 * specified shape. 
 * 
 * According to the Oracle API specification, this method will accept a 
 * {@code null} argument, but there is an open bug report (since 2004) 
 * that suggests this is wrong:
 * <p>
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206189">
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206189</a>
 * 
 * In this implementation, a {@code null} argument is not permitted.
 * 
 * @param s  the clip shape ({@code null} not permitted). 
 */
@Override
public void clip(Shape s) {
    if (this.clip == null) {
        setClip(s);
        return;
    }
    Shape ts = this.transform.createTransformedShape(s);
    Shape clipNew;
    if (!ts.intersects(this.clip.getBounds2D())) {
        clipNew = new Rectangle2D.Double();
    } else {
        Area a1 = new Area(ts);
        Area a2 = new Area(this.clip);
        a1.intersect(a2);
        clipNew = new Path2D.Double(a1);
    }
    this.clip = clipNew;
    if (!this.clippingDisabled) {
        this.gc.save();
        this.saveCount++;
        shapeToPath(this.clip);
        this.gc.clip();
    }
}
 
Example 6
Source File: BreadcrumbProgressBackground.java    From weblaf with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
@Override
protected Shape clip ( @NotNull final Graphics2D g2d, @NotNull final Rectangle bounds, @NotNull final C c, @NotNull final D d,
                       @NotNull final Shape shape )
{
    final Shape clippedShape;
    final Container parent = c.getParent ();
    if ( parent instanceof WebBreadcrumb )
    {
        final WebBreadcrumb breadcrumb = ( WebBreadcrumb ) parent;
        final double progress = breadcrumb.getProgress ( c );

        final boolean ltr = c.getComponentOrientation ().isLeftToRight ();
        final Rectangle shapeBounds = shape.getBounds ();
        final int pw = ( int ) Math.round ( shapeBounds.width * progress );
        shapeBounds.x = ltr ? shapeBounds.x : shapeBounds.x + shapeBounds.width - pw;
        shapeBounds.width = pw;

        final Area area = new Area ( shape );
        area.intersect ( new Area ( shapeBounds ) );
        clippedShape = area;
    }
    else
    {
        clippedShape = shape;
    }
    return clippedShape;
}
 
Example 7
Source File: PdfGraphics2D.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see Graphics2D#hit(Rectangle, Shape, boolean)
 */
public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
    if (onStroke) {
        s = stroke.createStrokedShape(s);
    }
    s = transform.createTransformedShape(s);
    Area area = new Area(s);
    if (clip != null)
        area.intersect(clip);
    return area.intersects(rect.x, rect.y, rect.width, rect.height);
}
 
Example 8
Source File: Cloud.java    From energy2d with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Area getShape(Rectangle2D.Float r) {
	// the positions and sizes of the circles must ensure that r is the bounding box
	float max = Math.max(r.width, r.height);
	Area a = new Area(new Ellipse2D.Float(r.x + r.width / 6, r.y, max / 2, max / 2));
	a.add(new Area(new Ellipse2D.Float(r.x, r.y + r.height / 2, max / 3, max / 3)));
	a.add(new Area(new Ellipse2D.Float(r.x + r.width / 3, r.y + r.height / 3, max / 2, max / 2)));
	a.add(new Area(new Ellipse2D.Float(r.x + 2 * r.width / 3, r.y + 2 * r.height / 3, r.width / 3, r.width / 3)));
	a.intersect(new Area(r));
	return a;
}
 
Example 9
Source File: ProductSceneView.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return the visible image area in pixel coordinates
 */
public Rectangle getVisibleImageBounds() {
    final ImageLayer imageLayer = getBaseImageLayer();

    if (imageLayer != null) {
        final RenderedImage image = imageLayer.getImage();
        final Area imageArea = new Area(new Rectangle(0, 0, image.getWidth(), image.getHeight()));
        final Area visibleImageArea = new Area(
                imageLayer.getModelToImageTransform().createTransformedShape(getVisibleModelBounds()));
        imageArea.intersect(visibleImageArea);
        return imageArea.getBounds();
    }

    return null;
}
 
Example 10
Source File: ShapeCollider.java    From salty-engine with Apache License 2.0 5 votes vote down vote up
@Override
public CollisionDetectionResult checkCollision(final GameObject object1, final GameObject object2) {

    final Collider otherCollider = getOtherCollider(object1.getCollider(), object2.getCollider());
    final GameObject otherGameObject = object1.getCollider() == otherCollider ? object1 : object2;

    final Area collisionArea = new Area(shape);

    switch (otherCollider.getType()) {
        case HITBOX_COLLIDER:
            collisionArea.intersect(new Area(otherGameObject.getHitbox().getTransform().getRect()));
            return new CollisionDetectionResult(!collisionArea.isEmpty(), new Transform(shape.getBounds()).getRelation(otherGameObject.getHitbox().getTransform()));

        case CIRCLE_COLLIDER:
            final CircleCollider collider = (CircleCollider) otherCollider;
            final Transform hitbox = collider.getHitbox();
            collisionArea.intersect(new Area(new Ellipse2D.Float(hitbox.getX(), hitbox.getY(), hitbox.getWidth(), hitbox.getHeight())));
            return new CollisionDetectionResult(!collisionArea.isEmpty(), new Transform(shape.getBounds()).getRelation(otherGameObject.getHitbox().getTransform()));

        case SHAPE_COLLIDER:
            final ShapeCollider shapeCollider = (ShapeCollider) otherCollider;
            collisionArea.intersect(new Area(shapeCollider.shape));
            return new CollisionDetectionResult(!collisionArea.isEmpty(), new Transform(shape.getBounds()).getRelation(new Transform(shapeCollider.shape.getBounds())));
    }

    return new CollisionDetectionResult(false, Directions.Direction.EMPTY);
}
 
Example 11
Source File: RegionOps.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public RectListImpl getIntersection(RectListImpl rli) {
    Area a2 = new Area(theArea);
    a2.intersect(((AreaImpl) rli).theArea);
    return new AreaImpl(a2);
}
 
Example 12
Source File: RegionOps.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public RectListImpl getIntersection(RectListImpl rli) {
    Area a2 = new Area(theArea);
    a2.intersect(((AreaImpl) rli).theArea);
    return new AreaImpl(a2);
}
 
Example 13
Source File: PageDrawer.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void fillPath(int windingRule) throws IOException
{
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    graphics.setPaint(getNonStrokingPaint());
    setClip();
    linePath.setWindingRule(windingRule);

    // disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
    // which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
    // note that we ignore paths with a width/height under 1 as these are fills used as strokes,
    // see PDFBOX-1658 for an example
    Rectangle2D bounds = linePath.getBounds2D();
    boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 &&
                                                     bounds.getHeight() > 1;
    if (noAntiAlias)
    {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                  RenderingHints.VALUE_ANTIALIAS_OFF);
    }

    Shape shape;
    if (!(graphics.getPaint() instanceof Color))
    {
        // apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901)
        Area area = new Area(linePath);
        area.intersect(new Area(graphics.getClip()));
        intersectShadingBBox(getGraphicsState().getNonStrokingColor(), area);
        shape = area;
    }
    else
    {
        shape = linePath;
    }
    if (isContentRendered())
    {
        graphics.fill(shape);
    }
    
    linePath.reset();

    if (noAntiAlias)
    {
        // JDK 1.7 has a bug where rendering hints are reset by the above call to
        // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
        setRenderingHints();
    }
}
 
Example 14
Source File: RegionOps.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public RectListImpl getIntersection(RectListImpl rli) {
    Area a2 = new Area(theArea);
    a2.intersect(((AreaImpl) rli).theArea);
    return new AreaImpl(a2);
}
 
Example 15
Source File: RegionOps.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public RectListImpl getIntersection(RectListImpl rli) {
    Area a2 = new Area(theArea);
    a2.intersect(((AreaImpl) rli).theArea);
    return new AreaImpl(a2);
}
 
Example 16
Source File: ShadowPainter.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void paintShadow(Component c, Graphics2D g, int x, int y, int width, int height) {
  ScaleContext ctx = ScaleContext.create(c, g);
  if (updateScaleContext(ctx)) {
    updateIcons(ctx);
  }
  final int leftSize = myCroppedLeft.getIconWidth();
  final int rightSize = myCroppedRight.getIconWidth();
  final int bottomSize = myCroppedBottom.getIconHeight();
  final int topSize = myCroppedTop.getIconHeight();

  int delta = myTopLeft.getIconHeight() + myBottomLeft.getIconHeight() - height;
  if (delta > 0) { // Corner icons are overlapping. Need to handle this
    Shape clip = g.getClip();

    int topHeight = myTopLeft.getIconHeight() - delta / 2;
    Area top = new Area(new Rectangle2D.Float(x, y, width, topHeight));
    if (clip != null) {
      top.intersect(new Area(clip));
    }
    g.setClip(top);

    myTopLeft.paintIcon(c, g, x, y);
    myTopRight.paintIcon(c, g, x + width - myTopRight.getIconWidth(), y);

    int bottomHeight = myBottomLeft.getIconHeight() - delta + delta / 2;
    Area bottom = new Area(new Rectangle2D.Float(x, y + topHeight, width, bottomHeight));
    if (clip != null) {
      bottom.intersect(new Area(clip));
    }
    g.setClip(bottom);

    myBottomLeft.paintIcon(c, g, x, y + height - myBottomLeft.getIconHeight());
    myBottomRight.paintIcon(c, g, x + width - myBottomRight.getIconWidth(), y + height - myBottomRight.getIconHeight());

    g.setClip(clip);
  }
  else {
    myTopLeft.paintIcon(c, g, x, y);
    myTopRight.paintIcon(c, g, x + width - myTopRight.getIconWidth(), y);
    myBottomLeft.paintIcon(c, g, x, y + height - myBottomLeft.getIconHeight());
    myBottomRight.paintIcon(c, g, x + width - myBottomRight.getIconWidth(), y + height - myBottomRight.getIconHeight());
  }

  fill(g, myCroppedTop, x, y, myTopLeft.getIconWidth(), width - myTopRight.getIconWidth(), true);
  fill(g, myCroppedBottom, x, y + height - bottomSize, myBottomLeft.getIconWidth(), width - myBottomRight.getIconWidth(), true);
  fill(g, myCroppedLeft, x, y, myTopLeft.getIconHeight(), height - myBottomLeft.getIconHeight(), false);
  fill(g, myCroppedRight, x + width - rightSize, y, myTopRight.getIconHeight(), height - myBottomRight.getIconHeight(), false);

  if (myBorderColor != null) {
    g.setColor(myBorderColor);
    g.drawRect(x + leftSize - 1, y + topSize - 1, width - leftSize - rightSize + 1, height - topSize - bottomSize + 1);
  }
}
 
Example 17
Source File: AdrTesting.java    From MercuryTrade with MIT License 4 votes vote down vote up
@Override
    public void paint(Graphics g, JComponent c) {
        //public void paintDeterminate(Graphics g, JComponent c) {
        Insets b = progressBar.getInsets(); // area for border
        int barRectWidth = progressBar.getWidth() - b.right - b.left;
        int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
        if (barRectWidth <= 0 || barRectHeight <= 0) {
            return;
        }

        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double degree = 360 * progressBar.getPercentComplete();
        double sz = Math.max(barRectWidth, barRectHeight);
        Shape outer = new Rectangle2D.Double(0, 0, sz, sz);
        Shape sector = new Arc2D.Double(-sz, -sz, sz * 3, sz * 3, 90 - degree, degree, Arc2D.PIE);

        Area foreground = new Area(sector);
        Area background = new Area(outer);

        foreground.intersect(background);

        g2.setPaint(new Color(0x505050));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
        g2.fill(background);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        try {
            BufferedImage read = ImageIO.read(getClass().getClassLoader().getResource("app/adr/vessel_vinktar.png"));
            g2.drawImage(read, 0, 0, (int) sz, (int) sz, null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
        g2.fill(foreground);

        g2.dispose();

//        // Deal with possible text painting
        if (progressBar.isStringPainted()) {
            paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
        }
    }
 
Example 18
Source File: NestWorldMapPane.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
public static GeneralPath[] assemblePathList(GeoPos[] geoPoints) {
    final GeneralPath path = new GeneralPath(GeneralPath.WIND_NON_ZERO, geoPoints.length + 8);
    final ArrayList<GeneralPath> pathList = new ArrayList<>(16);

    if (geoPoints.length > 1) {
        double lon, lat;
        double minLon = 0, maxLon = 0;

        boolean first = true;
        for (GeoPos gp : geoPoints) {
            lon = gp.getLon();
            lat = gp.getLat();
            if (first) {
                minLon = lon;
                maxLon = lon;
                path.moveTo(lon, lat);
                first = false;
            }
            if (lon < minLon) {
                minLon = lon;
            }
            if (lon > maxLon) {
                maxLon = lon;
            }
            path.lineTo(lon, lat);
        }
        //path.closePath();

        int runIndexMin = (int) Math.floor((minLon + 180) / 360);
        int runIndexMax = (int) Math.floor((maxLon + 180) / 360);

        if (runIndexMin == 0 && runIndexMax == 0) {
            // the path is completely within [-180, 180] longitude
            pathList.add(path);
            return pathList.toArray(new GeneralPath[pathList.size()]);
        }

        final Area pathArea = new Area(path);
        final GeneralPath pixelPath = new GeneralPath(GeneralPath.WIND_NON_ZERO);
        for (int k = runIndexMin; k <= runIndexMax; k++) {
            final Area currentArea = new Area(new Rectangle2D.Float(k * 360.0f - 180.0f, -90.0f, 360.0f, 180.0f));
            currentArea.intersect(pathArea);
            if (!currentArea.isEmpty()) {
                pathList.add(areaToPath(currentArea, -k * 360.0, pixelPath));
            }
        }
    }
    return pathList.toArray(new GeneralPath[pathList.size()]);
}
 
Example 19
Source File: Path.java    From gef with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Intersects the given areas.
 *
 * @param pa
 *            the first area to intersect
 * @param pb
 *            the second area to intersect
 * @return the intersection of the areas, i.e. the area covered by both
 *         areas
 */
public static Path intersect(Path pa, Path pb) {
	Area a = new Area(Geometry2AWT.toAWTPath(pa));
	Area b = new Area(Geometry2AWT.toAWTPath(pb));
	a.intersect(b);
	return AWT2Geometry.toPath(new Path2D.Double(a));
}
 
Example 20
Source File: GraphicsUtilities.java    From consulo with Apache License 2.0 3 votes vote down vote up
/**
 * Sets the clip on a graphics object by merging a supplied clip with the
 * existing one. The new clip will be an intersection of the old clip and
 * the supplied clip. The old clip shape will be returned. This is useful
 * for resetting the old clip after an operation is performed.
 *
 * @param g
 *            the graphics object to update
 * @param clip
 *            a new clipping region to add to the graphics clip. This may
 *            return {@code null} if the current clip is {@code null}.
 * @return the current clipping region of the supplied graphics object
 * @throws NullPointerException
 *             if any parameter is {@code null}
 */
public static Shape mergeClip(Graphics g, Shape clip) {
  Shape oldClip = g.getClip();
  if(oldClip == null) {
    g.setClip(clip);
    return null;
  }
  Area area = new Area(oldClip);
  area.intersect(new Area(clip));//new Rectangle(0,0,width,height)));
  g.setClip(area);
  return oldClip;
}