Example usage for java.awt Rectangle Rectangle

List of usage examples for java.awt Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(int x, int y, int width, int height) 

Source Link

Document

Constructs a new Rectangle whose upper-left corner is specified as (x,y) and whose width and height are specified by the arguments of the same name.

Usage

From source file:com.tools.image.IMagicHelper.java

/**
 * /* www.  java2  s  .  c  o  m*/
 * 
 * @param imgPath
 *            ?
 * @param toPath
 *            
 * @param w
 * @param h
 * @param x
 * @param y
 * @throws MagickException
 */
public static void cutImg(String imgPath, String toPath, int w, int h, int x, int y) throws MagickException {
    ImageInfo infoS = null;
    MagickImage image = null;
    MagickImage cropped = null;
    Rectangle rect = null;
    try {
        infoS = new ImageInfo(imgPath);
        image = new MagickImage(infoS);
        rect = new Rectangle(x, y, w, h);
        cropped = image.cropImage(rect);
        cropped.setFileName(toPath);
        cropped.writeImage(infoS);
    } finally {
        if (cropped != null) {
            cropped.destroyImages();
        }
    }
}

From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java

private void drawScale(Graphics scale, Point st, int width, int height) {
    Rectangle r = new Rectangle(st.x, st.y, width, height);
    if (width < 50 || height < 25) {
        return;/*from w  w w  . j a va 2s  .  c om*/
    }
    ScaleAndAxis sc = new ScaleAndAxis();
    sc.setColorFactory(colors);
    scale.translate(st.x, st.y);
    Rectangle bac = scale.getClipBounds();
    sc.setLocation(r.x, r.y);
    sc.setSize(r.width, r.height);
    sc.paintComponent(scale);
    scale.setClip(bac);
    scale.translate(-st.x, -st.y);
}

From source file:gdsc.smlm.ij.plugins.SpotInspector.java

public void run(String arg) {
    if (MemoryPeakResults.countMemorySize() == 0) {
        IJ.error(TITLE, "No localisations in memory");
        return;//from w w  w .  java  2 s.  c  o m
    }

    if (!showDialog())
        return;

    // Load the results
    results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }

    // Check if the original image is open
    ImageSource source = results.getSource();
    if (source == null) {
        IJ.error(TITLE, "Unknown original source image");
        return;
    }
    source = source.getOriginal();
    if (!source.open()) {
        IJ.error(TITLE, "Cannot open original source image: " + source.toString());
        return;
    }
    final float stdDevMax = getStandardDeviation(results);
    if (stdDevMax < 0) {
        // TODO - Add dialog to get the initial peak width
        IJ.error(TITLE, "Fitting configuration (for initial peak width) is not available");
        return;
    }

    // Rank spots
    rankedResults = new ArrayList<PeakResultRank>(results.size());
    final double a = results.getNmPerPixel();
    final double gain = results.getGain();
    final boolean emCCD = results.isEMCCD();

    for (PeakResult r : results.getResults()) {
        float[] score = getScore(r, a, gain, emCCD, stdDevMax);
        rankedResults.add(new PeakResultRank(r, score[0], score[1]));
    }
    Collections.sort(rankedResults);

    // Prepare results table. Get bias if necessary
    if (showCalibratedValues) {
        // Get a bias if required
        Calibration calibration = results.getCalibration();
        if (calibration.bias == 0) {
            GenericDialog gd = new GenericDialog(TITLE);
            gd.addMessage("Calibrated results requires a camera bias");
            gd.addNumericField("Camera_bias (ADUs)", calibration.bias, 2);
            gd.showDialog();
            if (!gd.wasCanceled()) {
                calibration.bias = Math.abs(gd.getNextNumber());
            }
        }
    }

    IJTablePeakResults table = new IJTablePeakResults(false, results.getName(), true);
    table.copySettings(results);
    table.setTableTitle(TITLE);
    table.setAddCounter(true);
    table.setShowCalibratedValues(showCalibratedValues);
    table.begin();

    // Add a mouse listener to jump to the frame for the clicked line
    textPanel = table.getResultsWindow().getTextPanel();

    // We must ignore old instances of this class from the mouse listeners
    id = ++currentId;
    textPanel.addMouseListener(this);

    // Add results to the table
    int n = 0;
    for (PeakResultRank rank : rankedResults) {
        rank.rank = n++;
        PeakResult r = rank.peakResult;
        table.add(r.peak, r.origX, r.origY, r.origValue, r.error, r.noise, r.params, r.paramsStdDev);
    }
    table.end();

    if (plotScore || plotHistogram) {
        // Get values for the plots
        float[] xValues = null, yValues = null;
        double yMin, yMax;

        int spotNumber = 0;
        xValues = new float[rankedResults.size()];
        yValues = new float[xValues.length];
        for (PeakResultRank rank : rankedResults) {
            xValues[spotNumber] = spotNumber + 1;
            yValues[spotNumber++] = recoverScore(rank.score);
        }

        // Set the min and max y-values using 1.5 x IQR 
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (float v : yValues)
            stats.addValue(v);
        if (removeOutliers) {
            double lower = stats.getPercentile(25);
            double upper = stats.getPercentile(75);
            double iqr = upper - lower;

            yMin = FastMath.max(lower - iqr, stats.getMin());
            yMax = FastMath.min(upper + iqr, stats.getMax());

            IJ.log(String.format("Data range: %f - %f. Plotting 1.5x IQR: %f - %f", stats.getMin(),
                    stats.getMax(), yMin, yMax));
        } else {
            yMin = stats.getMin();
            yMax = stats.getMax();

            IJ.log(String.format("Data range: %f - %f", yMin, yMax));
        }

        plotScore(xValues, yValues, yMin, yMax);
        plotHistogram(yValues, yMin, yMax);
    }

    // Extract spots into a stack
    final int w = source.getWidth();
    final int h = source.getHeight();
    final int size = 2 * radius + 1;
    ImageStack spots = new ImageStack(size, size, rankedResults.size());

    // To assist the extraction of data from the image source, process them in time order to allow 
    // frame caching. Then set the appropriate slice in the result stack
    Collections.sort(rankedResults, new Comparator<PeakResultRank>() {
        public int compare(PeakResultRank o1, PeakResultRank o2) {
            if (o1.peakResult.peak < o2.peakResult.peak)
                return -1;
            if (o1.peakResult.peak > o2.peakResult.peak)
                return 1;
            return 0;
        }
    });

    for (PeakResultRank rank : rankedResults) {
        PeakResult r = rank.peakResult;

        // Extract image
        // Note that the coordinates are relative to the middle of the pixel (0.5 offset)
        // so do not round but simply convert to int
        final int x = (int) (r.params[Gaussian2DFunction.X_POSITION]);
        final int y = (int) (r.params[Gaussian2DFunction.Y_POSITION]);

        // Extract a region but crop to the image bounds
        int minX = x - radius;
        int minY = y - radius;
        int maxX = FastMath.min(x + radius + 1, w);
        int maxY = FastMath.min(y + radius + 1, h);

        int padX = 0, padY = 0;
        if (minX < 0) {
            padX = -minX;
            minX = 0;
        }
        if (minY < 0) {
            padY = -minY;
            minY = 0;
        }
        int sizeX = maxX - minX;
        int sizeY = maxY - minY;

        float[] data = source.get(r.peak, new Rectangle(minX, minY, sizeX, sizeY));
        // Prevent errors with missing data
        if (data == null)
            data = new float[sizeX * sizeY];
        ImageProcessor spotIp = new FloatProcessor(sizeX, sizeY, data, null);

        // Pad if necessary, i.e. the crop is too small for the stack
        if (padX > 0 || padY > 0 || sizeX < size || sizeY < size) {
            ImageProcessor spotIp2 = spotIp.createProcessor(size, size);
            spotIp2.insert(spotIp, padX, padY);
            spotIp = spotIp2;
        }
        int slice = rank.rank + 1;
        spots.setPixels(spotIp.getPixels(), slice);
        spots.setSliceLabel(Utils.rounded(rank.originalScore), slice);
    }

    source.close();

    ImagePlus imp = Utils.display(TITLE, spots);
    imp.setRoi((PointRoi) null);

    // Make bigger      
    for (int i = 10; i-- > 0;)
        imp.getWindow().getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
}

From source file:gdsc.core.utils.ConvexHull.java

void calculateBounds(float[] xpoints, float[] ypoints, int npoints) {
    minX = Float.MAX_VALUE;/*from  w  w w.  j  a va  2s.  c o m*/
    minY = Float.MAX_VALUE;
    maxX = Float.MIN_VALUE;
    maxY = Float.MIN_VALUE;
    for (int i = 0; i < npoints; i++) {
        float x = xpoints[i];
        minX = Math.min(minX, x);
        maxX = Math.max(maxX, x);
        float y = ypoints[i];
        minY = Math.min(minY, y);
        maxY = Math.max(maxY, y);
    }
    int iMinX = (int) Math.floor(minX);
    int iMinY = (int) Math.floor(minY);
    bounds = new Rectangle(iMinX, iMinY, (int) (maxX - iMinX + 0.5), (int) (maxY - iMinY + 0.5));
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

protected Rectangle computeRectangles(PositionManager pman, BBoxManager bbman) {

    DecimalFormat mz_df = new DecimalFormat("0.0");

    Rectangle all_bbox = null;//w ww. j  a  v a 2 s.com
    rectangles = new HashMap<AnnotationObject, Rectangle>();
    rectangles_text = new HashMap<AnnotationObject, Rectangle>();
    rectangles_complete = new HashMap<AnnotationObject, Rectangle>();
    for (AnnotationObject a : theDocument.getAnnotations()) {

        // set scale
        theGlycanRenderer.getGraphicOptions().setScale(theOptions.SCALE_GLYCANS * theDocument.getScale(a));

        // compute bbox
        Point2D anchor = dataToScreenCoords(theDocument.getAnchor(a));
        Rectangle bbox = theGlycanRenderer.computeBoundingBoxes(a.getStructures(), false, false, pman, bbman,
                false);

        int x = (int) anchor.getX() - bbox.width / 2;
        int y = (int) anchor.getY() - bbox.height - theOptions.ANNOTATION_MARGIN
                - theOptions.ANNOTATION_MZ_SIZE;
        bbman.translate(x - bbox.x, y - bbox.y, a.getStructures());
        bbox.translate(x - bbox.x, y - bbox.y);

        // save bbox
        rectangles.put(a, bbox);

        // compute text bbox        
        String mz_text = mz_df.format(a.getPeakPoint().getX());
        Dimension mz_dim = textBounds(mz_text, theOptions.ANNOTATION_MZ_FONT, theOptions.ANNOTATION_MZ_SIZE);
        Rectangle text_bbox = new Rectangle((int) anchor.getX() - mz_dim.width / 2,
                (int) anchor.getY() - 2 * theOptions.ANNOTATION_MARGIN / 3 - mz_dim.height, mz_dim.width,
                mz_dim.height);

        // save text bbox
        rectangles_text.put(a, text_bbox);
        rectangles_complete.put(a, expand(union(bbox, text_bbox), theOptions.ANNOTATION_MARGIN / 2));

        // update all bbox
        all_bbox = union(all_bbox, bbox);
        all_bbox = union(all_bbox, text_bbox);
    }
    if (all_bbox == null)
        return new Rectangle(0, 0, 0, 0);
    return all_bbox;
}

From source file:DesktopManagerDemo.java

public void render(int[] counts) {
    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 15; j++) {
            m_arrays[j][i] = m_arrays[j][i + 1];
        }//from   w w w. j  av  a 2s.c om
    }
    for (int k = 0; k < 15; k++) {
        m_arrays[k][11] = counts[k];
    }
    paintImmediately(new Rectangle(20, 20, 505, 255));
}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

protected void showText(String text) {
    jTextArea1.append("[" + timestep + "] " + text + "\n");
    while (jTextArea1.getRows() > 50 && jTextArea1.getText().contains("\n"))
        jTextArea1.setText(jTextArea1.getText().substring(jTextArea1.getText().indexOf('\n') + 1));
    jTextArea1.repaint();//from w  w  w  .  j a v a  2  s  .  c  o m
    jTextArea1.scrollRectToVisible(new Rectangle(0, jTextArea1.getHeight() + 22, 1, 1));
}

From source file:de.fhg.igd.mapviewer.waypoints.CustomWaypointPainter.java

private void processWaypoint(W w, int minX, int minY, int width, int height, PixelConverter converter, int zoom,
        Graphics2D g) {/*from w w  w  .j ava 2 s  .c  om*/
    try {
        Point2D point = converter.geoToPixel(w.getPosition(), zoom);
        int x = (int) (point.getX() - minX);
        int y = (int) (point.getY() - minY);
        PixelConverter converterWrapper = new TranslationPixelConverterDecorator(converter, (int) point.getX(),
                (int) point.getY());
        g.translate(x, y);
        Rectangle gBounds = new Rectangle(minX - (int) point.getX(), minY - (int) point.getY(), width, height);
        renderer.paintWaypoint(g, converterWrapper, zoom, w, gBounds);
        g.translate(-x, -y);
    } catch (IllegalGeoPositionException e) {
        // waypoint not in map bounds or position invalid
        // log.warn("Error painting waypoint", e);
    }
}

From source file:org.geowebcache.layer.MetaTile.java

/**
 * Cuts the metaTile into the specified number of tiles, the actual number of tiles is
 * determined by metaX and metaY, not the width and height provided here.
 * /* ww w  .  j a  va2 s  .c  om*/
 * @param tileWidth
 *            width of each tile
 * @param tileHeight
 *            height of each tile
 * @return
 */
private Rectangle[] createTiles(int tileHeight, int tileWidth) {
    int tileCount = metaX * metaY;
    Rectangle[] tiles = new Rectangle[tileCount];

    for (int y = 0; y < metaY; y++) {
        for (int x = 0; x < metaX; x++) {
            int i = x * tileWidth + gutter[0];
            int j = (metaY - 1 - y) * tileHeight + gutter[3];

            // tiles[y * metaX + x] = createTile(i, j, tileWidth, tileHeight, useJAI);
            tiles[y * metaX + x] = new Rectangle(i, j, tileWidth, tileHeight);
        }
    }
    return tiles;
}

From source file:edu.umd.cfar.lamp.viper.geometry.BoundingBox.java

/**
 * Creates a new Box from a string representation.
 * // ww w  .  j a v  a  2s  .c  o  m
 * @param S
 *            a string representation, a series of 4 numbers representing
 *            the bottom left corner, width, and height
 * @throws BadDataException
 *             if the String is malformed
 */
public BoundingBox(String S) throws BadDataException {
    try {
        StringTokenizer st = new StringTokenizer(S);
        rect = new Rectangle(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()),
                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
        initPoly();
    } catch (NumberFormatException nfx) {
        rect = new Rectangle();
        initPoly();
        throw (new BadDataException("Bad bbox - " + S));
    }
}