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

The following examples show how to use java.awt.geom.Area#getBounds() . 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: MainPanel.java    From java-swing-tips with MIT License 7 votes vote down vote up
@Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  if (c instanceof JPopupMenu) {
    g2.clearRect(x, y, width, height);
  }
  double r = ARC;
  double w = width - 1d;
  double h = height - 1d;

  Area round = new Area(new RoundRectangle2D.Double(x, y, w, h, r, r));
  Rectangle b = round.getBounds();
  b.setBounds(b.x, b.y + ARC, b.width, b.height - ARC);
  round.add(new Area(b));

  Container parent = c.getParent();
  if (Objects.nonNull(parent)) {
    g2.setPaint(parent.getBackground());
    Area corner = new Area(new Rectangle2D.Double(x, y, width, height));
    corner.subtract(round);
    g2.fill(corner);
  }

  g2.setPaint(c.getForeground());
  g2.draw(round);
  g2.dispose();
}
 
Example 2
Source File: Pipe.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** @param area is expected in world coordinates. */
@Override
   public boolean intersects(final Area area, final double z_first, final double z_last) {
	// find lowest and highest Z
	double min_z = Double.MAX_VALUE;
	double max_z = 0;
	for (int i=0; i<n_points; i++) {
		final double laz =layer_set.getLayer(p_layer[i]).getZ();
		if (laz < min_z) min_z = laz;
		if (laz > max_z) max_z = laz;
	}
	if (z_last < min_z || z_first > max_z) return false;
	// check the roi
	for (int i=0; i<n_points; i++)  {
		final Polygon[] pol = getSubPerimeters(layer_set.getLayer(p_layer[i]));
		if (null == pol) continue;
		for (int k=0; k<pol.length; k++) {
			final Area a = new Area(pol[k]); // perimeters already in world coords
			a.intersect(area);
			final Rectangle r = a.getBounds();
			if (0 != r.width && 0 != r.height) return true;
		}
	}
	return false;
}
 
Example 3
Source File: Ball.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** @param area is expected in world coordinates. */
@Override
   public boolean intersects(final Area area, final double z_first, final double z_last) {
	// find lowest and highest Z
	double min_z = Double.MAX_VALUE;
	double max_z = 0;
	for (int i=0; i<n_points; i++) {
		final double laz =layer_set.getLayer(p_layer[i]).getZ();
		if (laz < min_z) min_z = laz;
		if (laz > max_z) max_z = laz;
	}
	if (z_last < min_z || z_first > max_z) return false;
	// check the roi
	for (int i=0; i<n_points; i++)  {
		final Rectangle[] rec = getSubPerimeters(layer_set.getLayer(p_layer[i]));
		for (int k=0; k<rec.length; k++) {
			final Area a = new Area(rec[k]); // subperimeters already in world coords
			a.intersect(area);
			final Rectangle r = a.getBounds();
			if (0 != r.width && 0 != r.height) return true;
		}
	}
	return false;
}
 
Example 4
Source File: BarsRetriever.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Section> getAreaSections (Area area,
                                       List<Section> allSections)
{
    final Rectangle areaBox = area.getBounds();
    final int xBreak = areaBox.x + areaBox.width;
    final List<Section> sections = new ArrayList<>();

    for (Section section : allSections) {
        final Rectangle sectionBox = section.getBounds();

        if (area.contains(sectionBox)) {
            sections.add(section);
        } else if (sectionBox.x >= xBreak) {
            break; // Since allSections are sorted by abscissa
        }
    }

    return sections;
}
 
Example 5
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
@Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  if (c instanceof JPopupMenu) {
    g2.clearRect(x, y, width, height);
  }
  double r = ARC;
  double w = width - 1d;
  double h = height - 1d;

  Area round = new Area(new RoundRectangle2D.Double(x, y, w, h, r, r));
  Rectangle b = round.getBounds();
  b.setBounds(b.x, b.y + ARC, b.width, b.height - ARC);
  round.add(new Area(b));

  Container parent = c.getParent();
  if (Objects.nonNull(parent)) {
    g2.setPaint(parent.getBackground());
    Area corner = new Area(new Rectangle2D.Double(x, y, width, height));
    corner.subtract(round);
    g2.fill(corner);
  }

  g2.setPaint(c.getForeground());
  g2.draw(round);
  g2.dispose();
}
 
Example 6
Source File: AreaList.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean intersects(final Layer layer, final Area area) {
	Object ob = ht_areas.get(layer.getId());
	if (null == ob) return false;
	if (AreaList.UNLOADED == ob) {
		ob = loadLayer(layer.getId());
		if (null == ob) return false;
	}
	final Area a = ((Area)ob).createTransformedArea(this.at);
	a.intersect(area);
	final Rectangle b = a.getBounds();
	return 0 != b.width && 0 != b.height;
}
 
Example 7
Source File: AreaList.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** @param area is expected in world coordinates. */
@Override
public boolean intersects(final Area area, final double z_first, final double z_last) {
	for (final Map.Entry<Long,Area> entry : ht_areas.entrySet()) {
		final Layer layer = layer_set.getLayer(((Long)entry.getKey()).longValue());
		if (layer.getZ() >= z_first && layer.getZ() <= z_last) {
			final Area a = ((Area)entry.getValue()).createTransformedArea(this.at);
			a.intersect(area);
			final Rectangle r = a.getBounds();
			if (0 != r.width && 0 != r.height) return true;
		}
	}
	return false;
}
 
Example 8
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 9
Source File: M.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the approximated area of the given Area object; Loader can be null; if not, it's used to secure memory space. */
static public final double measureArea(Area area, final Loader loader) {
	double sum = 0;
	try {
		Rectangle bounds = area.getBounds();
		double scale = 1;
		if (bounds.width > 2048 || bounds.height > 2048) { // TODO value 2048 should be reconsidered as a project property
			scale = 2048.0 / bounds.width;
		}
		if (0 == scale) {
			Utils.log("Can't measure: area too large, out of scale range for approximation.");
			return sum;
		}
		final AffineTransform at = new AffineTransform();
		at.translate(-bounds.x, -bounds.y);
		at.scale(scale, scale);
		area = area.createTransformedArea(at);
		bounds = area.getBounds();
		if (0 == bounds.width || 0 == bounds.height) {
			Utils.log("Can't measure: area too large, approximates zero.");
			return sum;
		}
		if (null != loader) loader.releaseToFit(bounds.width * bounds.height * 3);
		final BufferedImage bi = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_BYTE_INDEXED);
		final Graphics2D g = bi.createGraphics();
		g.setColor(Color.white);
		g.fill(area);
		final byte[] pixels = ((DataBufferByte)bi.getRaster().getDataBuffer()).getData(); // buffer.getData();
		for (int i=pixels.length-1; i>-1; i--) {
			//if (255 == (pixels[i]&0xff)) sum++;
			if (0 != pixels[i]) sum++;
		}
		bi.flush();
		g.dispose();
		if (1 != scale) sum = sum / (scale * scale);
	} catch (final Throwable e) {
		IJError.print(e);
	}
	return sum;
}
 
Example 10
Source File: TransformUI.java    From darklaf with MIT License 5 votes vote down vote up
/**
 * Primarily intended for use by {@link RepaintManager}.
 *
 * @param  rect  a rectangle
 * @param  layer the layer
 * @return       the argument rectangle if no {@link AffineTransform} is available, else a new rectangle
 */
public final Rectangle transform(final Rectangle rect, final JXLayer<? extends JComponent> layer) {
    AffineTransform at = getTransform(layer);
    if (at == null) {
        return rect;
    } else {
        Area area = new Area(rect);
        area.transform(at);
        return area.getBounds();
    }
}
 
Example 11
Source File: Mask.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new Mask object.
 *
 * @param area definition of the relevant area
 */
public Mask (Area area)
{
    this.area = area;

    rect = area.getBounds();
    bitmap = computeRelevantPoints(area);
}
 
Example 12
Source File: CurvesBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieve all arcs within reach from curve end (over some white gap)
 *
 * @param ext extension (on 'reverse' side)
 * @return the set of (new) reachable arcs
 */
private Set<ArcView> findReachableArcs (Extension ext)
{
    final Set<ArcView> reachableArcs = new LinkedHashSet<>();
    final Area area = defineExtArea(ext.curve);

    if (area != null) {
        // Check for reachable arcs in the extension area
        final Rectangle box = area.getBounds();
        final int xMax = (box.x + box.width) - 1;

        // Look for free-standing end points (with no junction point)
        for (Point end : skeleton.arcsEnds) {
            if (area.contains(end)) {
                final Arc arc = skeleton.arcsMap.get(end);

                if (!arc.isAssigned() && !ext.browsed.contains(arc)) {
                    // Check for lack of junction point
                    ArcView arcView = ext.curve.getArcView(arc, reverse);
                    Point pivot = arcView.getJunction(!reverse);

                    if (pivot == null) {
                        reachableArcs.add(arcView);
                        ext.browsed.add(arc);
                    }
                }
            } else if (end.x > xMax) {
                break; // Since list arcsEnds is sorted
            }
        }
    }

    return reachableArcs;
}
 
Example 13
Source File: M.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Test whether the areas intersect each other. */
static public final boolean intersects(final Area a1, final Area a2) {
	final Area b = new Area(a1);
	b.intersect(a2);
	final java.awt.Rectangle r = b.getBounds();
	return 0 != r.width && 0 != r.height;
}
 
Example 14
Source File: AreaMask.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new AreaMask object.
 *
 * @param area the defining absolute area
 */
public AreaMask (Area area)
{
    this.area = area;
    rect = area.getBounds();
}
 
Example 15
Source File: TextBuilder.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Retrieve the system-relevant lines, among all the lines OCR'ed at sheet level.
 *
 * @param buffer     the (sheet) pixel buffer
 * @param sheetLines the sheet raw OCR lines
 */
public void retrieveSystemLines (ByteProcessor buffer,
                                 List<TextLine> sheetLines)
{
    StopWatch watch = new StopWatch("Texts retrieveLines system#" + system.getId());
    watch.start("Pickup system lines");

    List<TextLine> systemLines = new ArrayList<>();

    // We pick up the words that are contained by system area
    // Beware: a text located between two systems must be deep copied to each system!
    final Area area = system.getArea();
    final Rectangle areaBounds = area.getBounds();

    for (TextLine sheetLine : sheetLines) {
        if (areaBounds.intersects(sheetLine.getBounds())) {
            TextLine line = new TextLine();

            for (TextWord sheetWord : sheetLine.getWords()) {
                final Rectangle wordBox = sheetWord.getBounds();

                if (area.contains(wordBox)) {
                    TextWord word = sheetWord.copy();
                    line.appendWord(word);
                }
            }

            if (!line.getWords().isEmpty()) {
                systemLines.add(line);
            }
        }
    }

    Collections.sort(systemLines, TextLine.byOrdinate(skew));

    watch.start("recomposeLines");
    systemLines = recomposeLines(systemLines);

    // Retrieve candidate sections and map words to glyphs
    watch.start("getSections");

    // Brand new sections (not the usual horizontal or vertical sheet sections)
    List<Section> relSections = getSections(buffer, systemLines);
    watch.start("mapGlyphs");
    mapGlyphs(systemLines, relSections, null);

    // Allocate corresponding inters based on role (Sentences or LyricLines of LyricItems)
    watch.start("createInters");
    createInters();

    watch.start("numberLyricLines()");
    numberLyricLines();

    if (constants.printWatch.isSet()) {
        watch.print();
    }

    if (logger.isDebugEnabled()) {
        dump("Retrieved lines", systemLines);
    }
}
 
Example 16
Source File: M.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
static public final boolean isEmpty(final Area area) {
	final Rectangle b = area.getBounds();
	return 0 == b.width || 0 == b.height;
}
 
Example 17
Source File: DisplayCanvas.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Smoothly move the canvas from its current position until the given rectangle is included within the srcRect.
 * If the given rectangle is larger than the srcRect, it will refuse to work (for now). */
public boolean animateBrowsing(final Rectangle target_, final Layer target_layer) {
	// Crop target to world's 2D dimensions
	final Area a = new Area(target_);
	a.intersect(new Area(display.getLayerSet().get2DBounds()));
	final Rectangle target = a.getBounds();
	if (0 == target.width || 0 == target.height) {
		return false;
	}
	// animate at all?
	if (this.srcRect.contains(target) && target_layer == display.getLayer()) {
		// So: don't animate, but at least highlight the target
		playHighlight(target);
		return false;
	}

	// The motion will be displaced by some screen pixels at every time step.
	final int ox = srcRect.x + srcRect.width/2;
	final int oy = srcRect.y + srcRect.height/2;
	final int tx = target.x + target.width/2;
	final int ty = target.y + target.height/2;
	final Vector2f v = new Vector2f(tx - ox, ty - oy);
	v.normalize();
	v.scale(20/(float)magnification);


	// The layer range
	final Layer start_layer = display.getLayer();
	/*
	int ithis = display.getLayerSet().indexOf(start_layer);
	int itarget = display.getLayerSet().indexOf(target_layer);
	final java.util.List<Layer> layers = display.getLayerSet().getLayers(ithis, itarget);
	*/
	final Calibration cal = display.getLayerSet().getCalibrationCopy();
	final double pixelWidth = cal.pixelWidth;
	final double pixelHeight = cal.pixelHeight;

	//final double dist_to_travel = Math.sqrt(Math.pow((tx - ox)*pixelWidth, 2) + Math.pow((ty - oy)*pixelHeight, 2)
	//				                + Math.pow((start_layer.getZ() - target_layer.getZ()) * pixelWidth, 2));

	// vector in calibrated coords between origin and target
	final Vector3d g = new Vector3d((tx - ox)*pixelWidth, (ty - oy)*pixelHeight, (target_layer.getZ() - start_layer.getZ())*pixelWidth);

	final ScheduledFuture<?>[] sf = new ScheduledFuture[1];
	sf[0] = animate(new Runnable() {
		@Override
		public void run() {
			if (DisplayCanvas.this.srcRect.contains(target)) {
				// reached destination
				if (display.getLayer() != target_layer) display.toLayer(target_layer);
				playHighlight(target);
				cancelAnimation(sf[0]);
			} else {
				setSrcRect(srcRect.x + (int)v.x, srcRect.y + (int)v.y, srcRect.width, srcRect.height);
				// which layer?
				if (start_layer != target_layer) {
					final int cx = srcRect.x + srcRect.width/2;
					final int cy = srcRect.y + srcRect.height/2;
					final double dist = Math.sqrt(Math.pow((cx - ox)*pixelWidth, 2) + Math.pow((cy - oy)*pixelHeight, 2)
								+ Math.pow((display.getLayer().getZ() - start_layer.getZ()) * pixelWidth, 2));

					final Vector3d gg = new Vector3d(g);
					gg.normalize();
					gg.scale((float)dist);
					final Layer la = display.getLayerSet().getNearestLayer(start_layer.getZ() + gg.z/pixelWidth);
					if (la != display.getLayer()) {
						display.toLayer(la);
					}
				}
				display.repaintAll2();
			}
		}
	}, 0, 50, TimeUnit.MILLISECONDS);
	return true;
}
 
Example 18
Source File: Inters.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Lookup the provided list of interpretations for those whose bounds
 * intersect the given area.
 *
 * @param inters the list of interpretations to search for
 * @param order  if the list is already sorted by some order, this may speedup the search
 * @param area   the intersecting area
 * @return the intersected interpretations found, perhaps empty but not null
 */
public static List<Inter> intersectedInters (List<Inter> inters,
                                             GeoOrder order,
                                             Area area)
{
    List<Inter> found = new ArrayList<>();
    Rectangle bounds = area.getBounds();
    double xMax = bounds.getMaxX();
    double yMax = bounds.getMaxY();

    for (Inter inter : inters) {
        if (inter.isRemoved()) {
            continue;
        }

        Rectangle iBox = inter.getBounds();

        if (area.intersects(iBox)) {
            found.add(inter);
        } else {
            switch (order) {
            case BY_ABSCISSA:

                if (iBox.x > xMax) {
                    return found;
                }

                break;

            case BY_ORDINATE:

                if (iBox.y > yMax) {
                    return found;
                }

                break;

            case NONE:
            }
        }
    }

    return found;
}
 
Example 19
Source File: AreaTree.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Find the nearest parent with a non-null, non-empty Area, and interpolate from {@code nd} to it.
 *
 * @param nd The node to start interpolating from, towards its nearest parent with an area.
 * @param node_centric If true, consider areas relative to the node coordinates. If false, relative to the overall AreaTree.
 *
 * @throws Exception */
public boolean interpolateTowardsParent(final Node<Area> nd, final boolean node_centric, final boolean always_use_distance_map) throws Exception {
	if (null == nd || null == nd.parent) return false;
	Area first = nd.getData();
	if (null == first || first.isEmpty()) {
		return false;
	}
	final LinkedList<Node<Area>> chain = new LinkedList<Node<Area>>();
	Node<Area> p = nd.parent;
	while (null != p && (null == p.getData() || p.getData().isEmpty())) {
		chain.add(p);
		p = p.parent;
	}
	if (p == nd.parent) {
		// Nothing to interpolate
		return false;
	}

	Area last = p.getData();

	int minx = 0, miny = 0;
	if (node_centric) {
		// Make areas relative to the nodes:
		first = first.createTransformedArea(new AffineTransform(1, 0, 0, 1, -nd.x, -nd.y));
		last = last.createTransformedArea(new AffineTransform(1, 0, 0, 1, -p.x, -p.y));
		// Remove translations
		final Rectangle bfirst = first.getBounds();
		final Rectangle blast = last.getBounds();
		minx = Math.min(bfirst.x, blast.x);
		miny = Math.min(bfirst.y, blast.y);
		final AffineTransform rmtrans = new AffineTransform(1, 0, 0, 1, -minx, -miny);
		first = first.createTransformedArea(rmtrans);
		last = last.createTransformedArea(rmtrans);
	}
	// Interpolate
	final Area[] as;
	if (!always_use_distance_map && first.isSingular() && last.isSingular()) {
		as = AreaUtils.singularInterpolation(first, last, chain.size());
	} else {
		as = AreaUtils.manyToManyInterpolation(first, last, chain.size());
	}
	// Assign each area
	for (final Area interpolated : as) {
		final Node<Area> target = chain.removeFirst();
		if (node_centric) {
			interpolated.transform(new AffineTransform(1, 0, 0, 1, minx + target.x, miny + target.y));
		}
		target.setData(interpolated);
	}

	return true;
}
 
Example 20
Source File: FileControlArrow.java    From whyline with MIT License 4 votes vote down vote up
protected void paintSelectedArrow(Graphics2D g, int labelLeft, int labelRight, int labelTop, int labelBottom) {
	
	if(toRange != null && toRange.first != null) {

		Area area = files.getAreaForTokenRange(toRange);
		if(area != null) {
			Rectangle tokens = area.getBounds();

			g.setColor(relationship.getColor(true));

			// Outline the tokens
			files.outline(g, toRange);
		
			// Get the boundaries of the selection.
			int tokenLeft = (int)tokens.getMinX();
			int tokenRight = (int) tokens.getMaxX();
			int tokenTop = (int) tokens.getMinY();
			int tokenBottom = (int) tokens.getMaxY();
			
			int labelX = tokenRight < (labelLeft + labelRight) / 2  ? labelLeft : labelRight;
			int labelY = labelBottom - descent;
			
			Line2D line = Util.getLineBetweenRectangleEdges(
					labelX, labelX + 1,
					labelY, labelY + 1,
					tokenLeft, tokenRight,
					tokenTop, tokenBottom
			);

			int xOff = 0;
			int yOff = 0;

			Util.drawQuadraticCurveArrow(g, (int)line.getX1(), (int)line.getY1(), (int)line.getX2(), (int)line.getY2(), xOff, yOff, true, relationship.getStroke(true));

			g.drawLine(labelLeft, labelY, labelRight, labelY);
			
		}
		
	}
	
}