Example usage for java.awt Rectangle intersection

List of usage examples for java.awt Rectangle intersection

Introduction

In this page you can find the example usage for java.awt Rectangle intersection.

Prototype

public Rectangle intersection(Rectangle r) 

Source Link

Document

Computes the intersection of this Rectangle with the specified Rectangle .

Usage

From source file:org.eclipse.jubula.rc.javafx.tester.adapter.TreeTableOperationContext.java

@Override
public Rectangle getVisibleRowBounds(final Rectangle rowBounds) {
    Rectangle result = EventThreadQueuerJavaFXImpl.invokeAndWait("getVisibleRowBounds", //$NON-NLS-1$
            new Callable<Rectangle>() {

                @Override/*w  ww  .  j a  va2 s .c o  m*/
                public Rectangle call() throws Exception {
                    TreeTableView<?> tree = getTree();
                    // Update the layout coordinates otherwise
                    // we would get old position values
                    tree.layout();
                    Rectangle visibleTreeBounds = new Rectangle(0, 0, Rounding.round(tree.getWidth()),
                            Rounding.round(tree.getHeight()));
                    return rowBounds.intersection(visibleTreeBounds);
                }
            });
    return result;
}

From source file:org.eclipse.jubula.rc.swing.tester.util.TreeOperationContext.java

/**
 * {@inheritDoc}/*from   w  ww . java  2 s  .  co  m*/
 */
public Rectangle getVisibleRowBounds(Rectangle rowBounds) {
    Rectangle visibleTreeBounds = ((JComponent) getTree()).getVisibleRect();
    Rectangle visibleRowBounds = visibleTreeBounds.intersection(rowBounds);
    return visibleRowBounds;
}

From source file:org.esa.nest.dat.views.polarview.PolarCanvas.java

private static void paintComponents(Container c, Graphics g) {
    if (!c.isShowing())
        return;// w ww  .  j  av a 2s.  c  om

    final int ncomponents = c.getComponentCount();
    final Rectangle clip = g.getClipBounds();

    int i = ncomponents - 1;
    while (i >= 0) {
        final Component component[] = c.getComponents();
        final Component comp = component[i];
        if (comp == null || !comp.isVisible())
            continue;
        final Rectangle bounds = comp.getBounds();
        Rectangle cr;
        if (clip == null)
            cr = new Rectangle(bounds);
        else
            cr = bounds.intersection(clip);
        if (cr.isEmpty())
            continue;

        final Graphics cg = g.create();
        cg.setClip(cr);
        cg.translate(bounds.x, bounds.y);
        try {
            comp.paint(cg);
        } catch (Throwable e) {
            //
        }

        cg.dispose();
        i--;
    }
}

From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java

private void computeRectIndirect(WritableRaster dest, Rectangle destRect) {
    try {//from  w w  w .  j  av a  2  s . com
        Path tile = decompressTile(tileIndex, getLevel());
        RenderedImage readTileImage = null;
        if (tile != null) {
            try (ImageReader imageReader = new ImageReader(tile)) {
                final DataBuffer dataBuffer = dest.getDataBuffer();
                int tileWidth = this.getTileWidth();
                int tileHeight = this.getTileHeight();
                final int fileTileX = destRect.x / tileLayout.tileWidth;
                final int fileTileY = destRect.y / tileLayout.tileHeight;
                int fileTileOriginX = destRect.x - fileTileX * tileLayout.tileWidth;
                int fileTileOriginY = destRect.y - fileTileY * tileLayout.tileHeight;
                Rectangle fileTileRect = tileDims.get(tile);
                if (fileTileRect == null) {
                    fileTileRect = new Rectangle(0, 0, imageReader.getImageWidth(),
                            imageReader.getImageHeight());
                    tileDims.put(tile, fileTileRect);
                }
                if (fileTileOriginX == 0 && tileLayout.tileWidth == tileWidth && fileTileOriginY == 0
                        && tileLayout.tileHeight == tileHeight
                        && tileWidth * tileHeight == dataBuffer.getSize()) {
                    readTileImage = imageReader.read();
                } else {
                    final Rectangle tileRect = new Rectangle(fileTileOriginX, fileTileOriginY, tileWidth,
                            tileHeight);
                    final Rectangle intersection = fileTileRect.intersection(tileRect);
                    if (!intersection.isEmpty()) {
                        readTileImage = imageReader.read(intersection);
                    }
                }
                if (readTileImage != null) {
                    Raster readBandRaster = readTileImage.getData().createChild(0, 0, readTileImage.getWidth(),
                            readTileImage.getHeight(), 0, 0, new int[] { bandIndex });
                    dest.setDataElements(dest.getMinX(), dest.getMinY(), readBandRaster);
                }
            } catch (IOException e) {
                logger.severe(e.getMessage());
            }
        }
    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java

private void computeRectDirect(WritableRaster dest, Rectangle destRect) {
    try (OpenJP2Decoder decoder = new OpenJP2Decoder(this.cacheDir, this.imageFile, this.bandIndex,
            this.dataType, getLevel(), 20, tileIndex)) {
        Raster readTileImage = null;
        final DataBuffer dataBuffer = dest.getDataBuffer();
        int tileWidth = this.getTileWidth();
        int tileHeight = this.getTileHeight();
        final int fileTileX = destRect.x / tileLayout.tileWidth;
        final int fileTileY = destRect.y / tileLayout.tileHeight;
        int fileTileOriginX = destRect.x - fileTileX * tileLayout.tileWidth;
        int fileTileOriginY = destRect.y - fileTileY * tileLayout.tileHeight;
        Dimension dimensions = decoder.getImageDimensions();
        Rectangle fileTileRect = new Rectangle(0, 0, dimensions.width, dimensions.height);

        if (fileTileOriginX == 0 && tileLayout.tileWidth == tileWidth && fileTileOriginY == 0
                && tileLayout.tileHeight == tileHeight && tileWidth * tileHeight == dataBuffer.getSize()) {
            readTileImage = decoder.read(null);
        } else {/*from w  w w .jav  a2s .c  o  m*/
            final Rectangle tileRect = new Rectangle(fileTileOriginX, fileTileOriginY, tileWidth, tileHeight);
            final Rectangle intersection = fileTileRect.intersection(tileRect);
            if (!intersection.isEmpty()) {
                readTileImage = decoder.read(intersection);
            }
        }
        if (readTileImage != null) {
            Raster readBandRaster = readTileImage.createChild(0, 0, readTileImage.getWidth(),
                    readTileImage.getHeight(), 0, 0, bands);
            dest.setDataElements(dest.getMinX(), dest.getMinY(), readBandRaster);
        }

    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java

protected void readTileData(File outputFile, int tileX, int tileY, int tileWidth, int tileHeight, int jp2TileX,
        int jp2TileY, int jp2TileWidth, int jp2TileHeight, short[] tileData, Rectangle destRect)
        throws IOException {

    // todo - we still have a synchronisation problem here: often zero areas are generated in a tile.
    // This does not happen, if we synchronise entire computeRect() on the instance, but it is less efficient.
    try (FileImageInputStream fis = new FileImageInputStream(outputFile)) {
        int jp2Width, jp2Height;
        final String[] tokens = fis.readLine().split(" ");
        long dataPos = fis.getStreamPosition();
        if (tokens.length != 6) {
            throw new IOException("Unexpected PGX tile image format");
        }// ww  w  .j  a v a 2 s  .co m

        // String pg = tokens[0];   // PG
        // String ml = tokens[1];   // ML
        // String plus = tokens[2]; // +
        try {
            // int jp2File.nbits = Integer.parseInt(tokens[3]);
            jp2Width = Integer.parseInt(tokens[4]);
            jp2Height = Integer.parseInt(tokens[5]);
        } catch (NumberFormatException e) {
            throw new IOException("Unexpected PGX tile image format");
        }
        if (jp2Width > jp2TileWidth || jp2Height > jp2TileHeight) {
            throw new IllegalStateException(
                    String.format("width (=%d) > tileWidth (=%d) || height (=%d) > tileHeight (=%d)", jp2Width,
                            jp2TileWidth, jp2Height, jp2TileHeight));
        }

        int jp2X = destRect.x - jp2TileX * jp2TileWidth;
        int jp2Y = destRect.y - jp2TileY * jp2TileHeight;
        if (jp2X < 0 || jp2Y < 0) {
            throw new IllegalStateException(String.format("jp2X (=%d) < 0 || jp2Y (=%d) < 0", jp2X, jp2Y));
        }

        if (jp2X == 0 && jp2Width == tileWidth && jp2Y == 0 && jp2Height == tileHeight
                && tileWidth * tileHeight == tileData.length) {
            fis.seek(dataPos);
            fis.readFully(tileData, 0, tileData.length);
        } else {
            final Rectangle jp2FileRect = new Rectangle(0, 0, jp2Width, jp2Height);
            final Rectangle tileRect = new Rectangle(jp2X, jp2Y, tileWidth, tileHeight);
            final Rectangle intersection = jp2FileRect.intersection(tileRect);
            if (!intersection.isEmpty()) {
                SystemUtils.LOG
                        .fine(String.format("%s: tile=(%d,%d): jp2FileRect=%s, tileRect=%s, intersection=%s\n",
                                outputFile, tileX, tileY, jp2FileRect, tileRect, intersection));
                long seekPos = dataPos
                        + S2Config.SAMPLE_BYTE_COUNT * (intersection.y * jp2Width + intersection.x);
                int tilePos = 0;
                for (int y = 0; y < intersection.height; y++) {
                    fis.seek(seekPos);
                    fis.readFully(tileData, tilePos, intersection.width);
                    seekPos += S2Config.SAMPLE_BYTE_COUNT * jp2Width;
                    tilePos += tileWidth;
                    for (int x = intersection.width; x < tileWidth; x++) {
                        tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_X_BOUNDS;
                    }
                }

                for (int y = intersection.height; y < tileHeight; y++) {
                    for (int x = 0; x < tileWidth; x++) {
                        tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_Y_BOUNDS;
                    }
                }
            } else {
                Arrays.fill(tileData, S2Config.FILL_CODE_NO_INTERSECTION);
            }
        }
    }
}

From source file:org.geotools.coverage.io.util.Utilities.java

/**
 * Evaluates the requested envelope and builds a new adjusted version of it fitting this coverage envelope.
 * //from   w  w w  .  j a  v  a  2  s. co m
 * <p>
 * While adjusting the requested envelope this methods also compute the source region as a rectangle which is suitable for a successive read
 * operation with {@link ImageIO} to do crop-on-read.
 * 
 * @param originalGridToWorld
 * 
 * @param coordinateReferenceSystem
 * 
 * 
 * @param requestedEnvelope is the envelope we are requested to load.
 * @param sourceRegion represents the area to load in raster space. This parameter cannot be null since it gets filled with whatever the crop
 *        region is depending on the <code>requestedEnvelope</code>.
 * @param requestedDim is the requested region where to load data of the specified envelope.
 * @param readGridToWorld the Grid to world transformation to be used
 * @param wgs84BaseEnvelope2D
 * @return the adjusted requested envelope, empty if no requestedEnvelope has been specified, {@code null} in case the requested envelope does not
 *         intersect the coverage envelope or in case the adjusted requested envelope is covered by a too small raster region (an empty region).
 * 
 * @throws DataSourceException in case something bad occurs
 */
public static GeneralEnvelope evaluateRequestedParams(GridEnvelope originalGridRange, Envelope2D baseEnvelope2D,
        CoordinateReferenceSystem spatialReferenceSystem2D, MathTransform originalGridToWorld,
        GeneralEnvelope requestedEnvelope, Rectangle sourceRegion, Rectangle requestedDim,
        MathTransform2D readGridToWorld, Envelope2D wgs84BaseEnvelope2D) throws DataSourceException {

    GeneralEnvelope adjustedRequestedEnvelope = new GeneralEnvelope(2);
    GeneralGridEnvelope baseGridRange = (GeneralGridEnvelope) originalGridRange;

    try {
        // ////////////////////////////////////////////////////////////////
        //
        // Check if we have something to load by intersecting the
        // requested envelope with the bounds of this data set.
        //
        // ////////////////////////////////////////////////////////////////
        if (requestedEnvelope != null) {
            final GeneralEnvelope requestedEnvelope2D = Utilities.getRequestedEnvelope2D(requestedEnvelope);

            // ////////////////////////////////////////////////////////////
            //
            // INTERSECT ENVELOPES AND CROP Destination REGION
            //
            // ////////////////////////////////////////////////////////////
            adjustedRequestedEnvelope = Utilities.getIntersection(baseEnvelope2D, spatialReferenceSystem2D,
                    requestedEnvelope2D, requestedDim, readGridToWorld, wgs84BaseEnvelope2D);
            if (adjustedRequestedEnvelope == null)
                return null;

            // /////////////////////////////////////////////////////////////////////
            //
            // CROP SOURCE REGION
            //
            // /////////////////////////////////////////////////////////////////////
            sourceRegion.setRect(Utilities.getCropRegion(adjustedRequestedEnvelope,
                    Utilities.getOriginalGridToWorld(originalGridToWorld, PixelInCell.CELL_CORNER)));
            if (sourceRegion.isEmpty()) {
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO, "Too small envelope resulting in empty cropped raster region");
                }
                return null;
                // TODO: Future versions may define a 1x1 rectangle starting
                // from the lower coordinate
            }
            if (!sourceRegion.intersects(baseGridRange.toRectangle()) || sourceRegion.isEmpty())
                throw new DataSourceException("The crop region is invalid.");
            sourceRegion.setRect(sourceRegion.intersection(baseGridRange.toRectangle()));

            if (LOGGER.isLoggable(Level.FINE)) {
                StringBuilder sb = new StringBuilder("Adjusted Requested Envelope = ")
                        .append(adjustedRequestedEnvelope.toString()).append("\n")
                        .append("Requested raster dimension = ").append(requestedDim.toString()).append("\n")
                        .append("Corresponding raster source region = ").append(sourceRegion.toString());
                LOGGER.log(Level.FINE, sb.toString());
            }

        } else {
            // don't use the source region. Set an empty one
            sourceRegion.setBounds(new Rectangle(0, 0, Integer.MIN_VALUE, Integer.MIN_VALUE));
        }
    } catch (TransformException e) {
        throw new DataSourceException("Unable to create a coverage for this source", e);
    } catch (FactoryException e) {
        throw new DataSourceException("Unable to create a coverage for this source", e);
    }
    return adjustedRequestedEnvelope;
}

From source file:org.mitre.mpf.wfm.camel.operations.detection.trackmerging.TrackMergingProcessor.java

private boolean intersects(Track track1, Track track2, double segMinOverlap) {
    if (!StringUtils.equalsIgnoreCase(track1.getType(), track2.getType())) {
        // Tracks of different types should not be candidates for merger. Ex: It would make no sense to merge a motion and speech track.
        return false;
    } else if (StringUtils.equalsIgnoreCase(track1.getType(), "SPEECH")) {
        // Speech tracks should not be candidates for merger.
        return false;
    }/*from w ww .  j a va2 s. c om*/

    Detection track1End = track1.getDetections().last();
    Detection track2End = track2.getDetections().first();

    Detection first = (track1End.getMediaOffsetFrame() < track2End.getMediaOffsetFrame()) ? track1End
            : track2End;
    Detection second = (first == track1End) ? track2End : track1End;

    Rectangle rectangle1 = new Rectangle(first.getX(), first.getY(), first.getWidth(), first.getHeight());
    Rectangle rectangle2 = new Rectangle(second.getX(), second.getY(), second.getWidth(), second.getHeight());

    if (rectangle1.getWidth() == 0 || rectangle2.getWidth() == 0 || rectangle1.getHeight() == 0
            || rectangle1.getHeight() == 0) {
        return false;
    }

    Rectangle intersection = rectangle1.intersection(rectangle2);
    if (intersection.isEmpty()) {
        return false;
    }

    double intersectArea = intersection.getHeight() * intersection.getWidth();
    double unionArea = (rectangle2.getHeight() * rectangle2.getWidth())
            + (rectangle1.getHeight() * rectangle1.getWidth()) - intersectArea;
    double percentOverlap = intersectArea / unionArea;

    return percentOverlap > segMinOverlap;
}

From source file:org.pentaho.reporting.libraries.designtime.swing.LibSwingUtil.java

/**
 * Positions the specified dialog at a position relative to its parent.
 *
 * @param dialog            the dialog to be positioned.
 * @param horizontalPercent the relative location.
 * @param verticalPercent   the relative location.
 *///from w ww. j  a  va2  s  .  co  m
public static void positionDialogRelativeToParent(final Dialog dialog, final double horizontalPercent,
        final double verticalPercent) {
    final Container parent = dialog.getParent();
    if (parent == null || (parent.isVisible() == false)) {
        positionFrameOnScreen(dialog, horizontalPercent, verticalPercent);
        return;
    }

    final Dimension d = dialog.getSize();
    final Dimension p = parent.getSize();

    final int baseX = parent.getX();
    final int baseY = parent.getY();

    final int parentPointX = baseX + (int) (horizontalPercent * p.width);
    final int parentPointY = baseY + (int) (verticalPercent * p.height);

    final int dialogPointX = parentPointX - (int) (horizontalPercent * d.width);
    final int dialogPointY = parentPointY - (int) (verticalPercent * d.height);

    // make sure the dialog fits completely on the screen...
    final Rectangle s = parent.getGraphicsConfiguration().getBounds();
    final Rectangle r = new Rectangle(dialogPointX, dialogPointY, d.width, d.height);
    final Rectangle intersectedDialogBounds = r.intersection(s);
    if (intersectedDialogBounds.width < d.width) {
        r.x = s.width - d.width;
        r.width = d.width;
    }
    if (intersectedDialogBounds.height < d.height) {
        r.y = s.height - d.height;
        r.height = d.height;
    }
    final Rectangle finalIntersection = r.intersection(s);
    dialog.setBounds(finalIntersection);
}

From source file:org.uva.itast.blended.omr.pages.PageImage.java

/**
 * @param rectMM bounding box in milimeters
 * @see #getSubimage(double, double, double, double, int)
 * @return/*from w w  w.  j a va2  s.  co m*/
 */
public SubImage getSubimage(Rectangle2D rectMM, int imageType) {

    Rectangle rect = this.toPixels(rectMM);
    if (logger.isDebugEnabled()) {
        logger.debug("Subimage " + rectMM + " mm " + rect + " px.");
    }
    PagePoint upperLeft = new PagePoint(this, rectMM.getX(), rectMM.getY());

    Point reference = upperLeft.getPixelsPoint();

    BufferedImage originalImage = getImage();
    Rectangle originalRect = new Rectangle(originalImage.getWidth(), originalImage.getHeight());
    // copy what is available from image
    Rectangle available = rect.intersection(originalRect);

    BufferedImage originalSubImage = originalImage.getSubimage(available.x, available.y, available.width,
            available.height);

    //rotate image
    SubImage subimage = new SubImage(rect.width, rect.height, imageType);
    subimage.setReference(reference);
    subimage.setBoundingBox(rect);
    subimage.setCapturedBoundingBox(available);

    Graphics2D g = subimage.createGraphics();
    g.drawImage(originalSubImage, available.x - rect.x, available.y - rect.y, null);

    return subimage;
}