Example usage for java.awt Rectangle getHeight

List of usage examples for java.awt Rectangle getHeight

Introduction

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

Prototype

public double getHeight() 

Source Link

Document

Returns the height of the bounding Rectangle in double precision.

Usage

From source file:SciTK.Plot.java

/**
 * Exports a JFreeChart to a PS file using Adobe XML graphics library.
 * //  w w w.j ava 2s .  c om
 * @param chart JFreeChart to export
 * @param bounds the dimensions of the viewport
 * @param psFile the output file.
 * @param mode the file write mode ("ps","eps")
 * @throws IOException if writing the file fails.
 */
protected void exportChartAsPS(JFreeChart chart, Rectangle bounds, File psFile, String mode)
        throws IOException {
    // see http://xmlgraphics.apache.org/commons/postscript.html#creating-eps

    // set up file:
    OutputStream outputStream = new FileOutputStream(psFile);

    AbstractPSDocumentGraphics2D g2d;
    if (mode == "ps")
        g2d = new PSDocumentGraphics2D(false);
    else
        g2d = new EPSDocumentGraphics2D(false);

    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    //Set up the document size
    g2d.setupDocument(outputStream, (int) bounds.getWidth(), (int) bounds.getHeight());
    //out is the OutputStream to write the EPS to

    // draw the chart to g2d:
    chart.draw(g2d, bounds);

    // write and close file:    
    g2d.finish(); //Wrap up and finalize the EPS file
    outputStream.flush();
    outputStream.close();
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private boolean redraw() {
    Village[][] mVisibleVillages = DataHolder.getSingleton().getVillages();

    if (mVisibleVillages == null || mBuffer == null) {
        return false;
    }/* w ww  .j  ava  2s.com*/

    Graphics2D g2d = (Graphics2D) mBuffer.getGraphics();
    Composite tempC = g2d.getComposite();
    //clear
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
    g2d.fillRect(0, 0, mBuffer.getWidth(), mBuffer.getHeight());

    //reset composite
    g2d.setComposite(tempC);

    boolean markPlayer = GlobalOptions.getProperties().getBoolean("mark.villages.on.minimap");
    if (ServerSettings.getSingleton().getMapDimension() == null) {
        //could not draw minimap if dimensions are not loaded yet
        return false;
    }
    boolean showBarbarian = GlobalOptions.getProperties().getBoolean("show.barbarian");

    Color DEFAULT = Constants.DS_DEFAULT_MARKER;
    try {
        int mark = Integer.parseInt(GlobalOptions.getProperty("default.mark"));
        if (mark == 0) {
            DEFAULT = Constants.DS_DEFAULT_MARKER;
        } else if (mark == 1) {
            DEFAULT = Color.RED;
        } else if (mark == 2) {
            DEFAULT = Color.WHITE;
        }
    } catch (Exception e) {
        DEFAULT = Constants.DS_DEFAULT_MARKER;
    }

    Rectangle mapDim = ServerSettings.getSingleton().getMapDimension();
    double wField = mapDim.getWidth() / (double) visiblePart.width;
    double hField = mapDim.getHeight() / (double) visiblePart.height;

    UserProfile profile = GlobalOptions.getSelectedProfile();
    Tribe currentTribe = InvalidTribe.getSingleton();
    if (profile != null) {
        currentTribe = profile.getTribe();
    }

    for (int i = visiblePart.x; i < (visiblePart.width + visiblePart.x); i++) {
        for (int j = visiblePart.y; j < (visiblePart.height + visiblePart.y); j++) {
            Village v = mVisibleVillages[i][j];
            if (v != null) {
                Color markerColor = null;
                boolean isLeft = false;
                if (v.getTribe() == Barbarians.getSingleton()) {
                    isLeft = true;
                } else {
                    if ((currentTribe != null) && (v.getTribe().getId() == currentTribe.getId())) {
                        //village is owned by current player. mark it dependent on settings
                        if (markPlayer) {
                            markerColor = Color.YELLOW;
                        }
                    } else {
                        try {
                            Marker marker = MarkerManager.getSingleton().getMarker(v.getTribe());
                            if (marker != null && !marker.isShownOnMap()) {
                                marker = null;
                                markerColor = DEFAULT;
                            }

                            if (marker == null) {
                                marker = MarkerManager.getSingleton().getMarker(v.getTribe().getAlly());
                                if (marker != null && marker.isShownOnMap()) {
                                    markerColor = marker.getMarkerColor();
                                }
                            } else {
                                if (marker.isShownOnMap()) {
                                    markerColor = marker.getMarkerColor();
                                }
                            }
                        } catch (Exception e) {
                            markerColor = null;
                        }
                    }
                }

                if (!isLeft) {
                    if (markerColor != null) {
                        g2d.setColor(markerColor);
                    } else {
                        g2d.setColor(DEFAULT);
                    }
                    g2d.fillRect((int) Math.round((i - visiblePart.x) * wField),
                            (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField),
                            (int) Math.floor(hField));
                } else {
                    if (showBarbarian) {
                        g2d.setColor(Color.LIGHT_GRAY);
                        g2d.fillRect((int) Math.round((i - visiblePart.x) * wField),
                                (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField),
                                (int) Math.floor(hField));
                    }
                }
            }
        }
    }

    try {
        if (GlobalOptions.getProperties().getBoolean("map.showcontinents")) {
            g2d.setColor(Color.BLACK);
            Composite c = g2d.getComposite();
            Composite a = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
            Font f = g2d.getFont();
            Font t = new Font("Serif", Font.BOLD, (int) Math.round(30 * hField));
            g2d.setFont(t);
            int fact = 10;
            int mid = (int) Math.round(50 * wField);

            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    g2d.setComposite(a);

                    String conti = "K" + (j * 10 + i);
                    Rectangle2D bounds = g2d.getFontMetrics(t).getStringBounds(conti, g2d);
                    int cx = i * fact * 10 - visiblePart.x;
                    int cy = j * fact * 10 - visiblePart.y;
                    cx = (int) Math.round(cx * wField);
                    cy = (int) Math.round(cy * hField);
                    g2d.drawString(conti, (int) Math.rint(cx + mid - bounds.getWidth() / 2),
                            (int) Math.rint(cy + mid + bounds.getHeight() / 2));
                    g2d.setComposite(c);
                    int wk = 100;
                    int hk = 100;

                    if (i == 9) {
                        wk -= 1;
                    }
                    if (j == 9) {
                        hk -= 1;
                    }

                    g2d.drawRect(cx, cy, (int) Math.round(wk * wField), (int) Math.round(hk * hField));
                }
            }
            g2d.setFont(f);
        }
    } catch (Exception e) {
        logger.error("Creation of Minimap failed", e);
    }
    g2d.dispose();
    return true;
}

From source file:edu.stanford.epadd.launcher.Splash.java

public Splash() {
    final SplashScreen splash = (System.getProperty("nobrowseropen") == null) ? SplashScreen.getSplashScreen()
            : null;/* w  w w. jav  a  2  s  .  co m*/
    if (splash == null) {
        System.out.println("SplashScreen.getSplashScreen() returned null");
        return;
    }
    Rectangle r = splash.getBounds();
    g = splash.createGraphics();
    if (g == null) {
        System.out.println("splash.createGraphics() returned null");
        return;
    }

    /* code to prevent text from appearing too pixelated - https://stackoverflow.com/questions/31536952/how-to-fix-text-quality-in-java-graphics */
    Map<?, ?> desktopHints = (Map<?, ?>) Toolkit.getDefaultToolkit()
            .getDesktopProperty("awt.font.desktophints");
    if (desktopHints != null) {
        g.setRenderingHints(desktopHints);
    }
    System.out.println("splash url = " + splash.getImageURL() + " w=" + r.getWidth() + " h=" + r.getHeight()
            + " size=" + r.getSize() + " loc=" + r.getLocation());
    //      setVisible(true);
    //      toFront();
}

From source file:edu.umn.cs.spatialHadoop.core.OGCESRIShape.java

@Override
public void draw(Graphics g, Rectangle fileMBR, int imageWidth, int imageHeight, double scale) {
    OGCGeometry geom = this.geom;
    Color shape_color = g.getColor();
    if (geom instanceof OGCGeometryCollection) {
        OGCGeometryCollection geom_coll = (OGCGeometryCollection) geom;
        for (int i = 0; i < geom_coll.numGeometries(); i++) {
            OGCGeometry sub_geom = geom_coll.geometryN(i);
            // Recursive call to draw each geometry
            new OGCESRIShape(sub_geom).draw(g, fileMBR, imageWidth, imageHeight, scale);
        }//from w ww.  j a  va  2  s  . c o  m
    } else if (geom.getEsriGeometry() instanceof MultiPath) {
        MultiPath path = (MultiPath) geom.getEsriGeometry();
        double sub_geom_alpha = path.calculateLength2D() * scale;
        int color_alpha = sub_geom_alpha > 1.0 ? 255 : (int) Math.round(sub_geom_alpha * 255);

        if (color_alpha == 0)
            return;

        int[] xpoints = new int[path.getPointCount()];
        int[] ypoints = new int[path.getPointCount()];

        for (int i = 0; i < path.getPointCount(); i++) {
            double px = path.getPoint(i).getX();
            double py = path.getPoint(i).getY();

            // Transform a point in the polygon to image coordinates
            xpoints[i] = (int) Math.round((px - fileMBR.x1) * imageWidth / fileMBR.getWidth());
            ypoints[i] = (int) Math.round((py - fileMBR.y1) * imageHeight / fileMBR.getHeight());
        }

        // Draw the polygon
        g.setColor(new Color((shape_color.getRGB() & 0x00FFFFFF) | (color_alpha << 24), true));
        if (path instanceof Polygon)
            g.drawPolygon(xpoints, ypoints, path.getPointCount());
        else if (path instanceof Polyline)
            g.drawPolyline(xpoints, ypoints, path.getPointCount());
    }
}

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

public Rectangle2D computeSizeData(AnnotationObject a) {
    // compute bbox
    theGlycanRenderer.getGraphicOptions().setScale(theOptions.SCALE_GLYCANS * theDocument.getScale(a));
    Rectangle bbox = theGlycanRenderer.computeBoundingBoxes(a.getStructures(), false, false,
            new PositionManager(), new BBoxManager(), false);

    // compute text bbox        
    DecimalFormat mz_df = new DecimalFormat("0.0");
    String mz_text = mz_df.format(a.getPeakPoint().getX());
    Dimension mz_dim = textBounds(mz_text, theOptions.ANNOTATION_MZ_FONT, theOptions.ANNOTATION_MZ_SIZE);

    // update bbox
    double width = Math.max(bbox.getWidth(), mz_dim.getWidth());
    double height = bbox.getHeight() + theOptions.ANNOTATION_MARGIN + theOptions.ANNOTATION_MZ_SIZE;
    return new Rectangle2D.Double(0, 0, screenToDataX(width), screenToDataY(height));
}

From source file:com.t3.macro.api.views.TokenView.java

/**
 * Returns a set of the parts of a token that can be seen by this token.
 * @param target the token of which we want to check what this token can see
 * @return the set of visible token parts
 *//*from  w ww . j a va2s. c o  m*/
public EnumSet<TokenPart> getVisibleTokenParts(TokenView target) {
    if (!token.getHasSight())
        return EnumSet.noneOf(TokenPart.class);

    ZoneRenderer zr = TabletopTool.getFrame().getZoneRenderer(token.getZone());
    Zone zone = zr.getZone();
    Area tokensVisibleArea = zr.getZoneView().getVisibleArea(token);
    if (tokensVisibleArea == null)
        return EnumSet.noneOf(TokenPart.class);
    if (target == null)
        throw new NullPointerException();
    if (!target.isVisible() || (target.token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(target.token))) {
        return EnumSet.noneOf(TokenPart.class);
    }
    Grid grid = zone.getGrid();

    Rectangle bounds = target.token.getFootprint(grid).getBounds(grid,
            grid.convert(new ZonePoint(target.token.getX(), target.token.getY())));
    if (!target.token.isSnapToGrid())
        bounds = target.token.getBounds(zone);

    EnumSet<TokenPart> ret = EnumSet.noneOf(TokenPart.class);

    int x = (int) bounds.getX();
    int y = (int) bounds.getY();
    int w = (int) bounds.getWidth();
    int h = (int) bounds.getHeight();

    int halfX = x + (w) / 2;
    int halfY = y + (h) / 2;
    if (tokensVisibleArea.intersects(bounds)) {
        if (tokensVisibleArea.contains(new Point(x, y)))
            ret.add(TokenPart.TOP_LEFT);
        if (tokensVisibleArea.contains(new Point(x, y + h)))
            if (tokensVisibleArea.contains(new Point(x + w, y)))
                ret.add(TokenPart.TOP_RIGHT);
        if (tokensVisibleArea.contains(new Point(x + w, y + h)))
            ret.add(TokenPart.BOTTOM_LEFT);
        if (tokensVisibleArea.contains(new Point(halfX, halfY)))
            ret.add(TokenPart.BOTTOM_RIGHT);
    }
    return ret;
}

From source file:Creator.WidgetPanel.java

public String createWidget(WidgetLink wl, Rectangle rect, int[] io_id) {

    if (widgetList.containsKey(wl.getWidgetCodeName())) {
        WidgetCode wc = widgetList.get(wl.getWidgetCodeName());
        Point per = wl.getPositionPercentage();

        int xPos = rect.x + (int) (per.getX() * rect.getWidth() / 100.0);
        int yPos = rect.y + (int) (per.getY() * rect.getHeight() / 100.0);

        String code = wc.getFullWidgetText();

        code = code.replace("`%IO_ID%`", String.valueOf(io_id[0])).replace("`%XPOS%`", String.valueOf(xPos))
                .replace("`%YPOS%`", String.valueOf(yPos));

        for (int i = 1; i < io_id.length; i++) {
            code = code.replace("`%IO_ID" + String.valueOf(i + 1) + "%`", String.valueOf(io_id[i]));
        }// w ww  .j a  v a  2  s. c om

        for (Map.Entry<String, String> entry : wl.getVariables().entrySet()) {

            code = code.replace(entry.getKey(), entry.getValue());
        }

        return code;
    } else {
        System.out.println("Could not find a link for the widget named: " + wl.getWidgetCodeName());
        return "";
    }
}

From source file:knop.psfj.BeadImage.java

/**
 * Gets the enlarged frame.//from ww w . j  a  va2  s  .  c o m
 *
 * @param r the r
 * @return the enlarged frame
 */
public Rectangle getEnlargedFrame(Rectangle r) {
    Rectangle rn = new Rectangle();

    int f = frameSize;

    if (frameSize * frameSize >= imageWidth * imageHeight * 0.8) {
        rn.setLocation(0, 0);
        rn.setSize(imageWidth, imageHeight);
        return rn;
    }

    int x = MathUtils.round(r.getX() + r.getWidth() / 2 - f / 2);

    int y = MathUtils.round(r.getY() + r.getHeight() / 2 - f / 2);

    x -= 1;
    y -= 1;

    int w = f;
    int h = f;
    rn.setLocation(x, y);
    rn.setSize(w, h);

    return rn;
}

From source file:com.joliciel.jochre.graphics.SegmenterImpl.java

void removeOversizedShapes(List<Shape> shapes) {
    LOG.debug("########## removeOversizedShapes #########");
    Mean shapeHeightMean = new Mean();
    Mean shapeWidthMean = new Mean();

    for (Shape shape : shapes) {
        shapeHeightMean.increment(shape.getHeight());
        shapeWidthMean.increment(shape.getWidth());
    }//from w w w  . j  ava  2s.c o  m

    double heightMean = shapeHeightMean.getResult();
    double widthMean = shapeWidthMean.getResult();
    LOG.debug("heightMean: " + heightMean);
    LOG.debug("widthMean: " + widthMean);

    shapeHeightMean = new Mean();
    shapeWidthMean = new Mean();
    StandardDeviation shapeHeightStdDev = new StandardDeviation();
    for (Shape shape : shapes) {
        if (shape.getHeight() > heightMean && shape.getHeight() < (heightMean * 2.0)
                && shape.getWidth() > widthMean && shape.getWidth() < (widthMean * 2.0)) {
            shapeHeightMean.increment(shape.getHeight());
            shapeHeightStdDev.increment(shape.getHeight());
            shapeWidthMean.increment(shape.getWidth());
        }
    }

    heightMean = shapeHeightMean.getResult();
    widthMean = shapeWidthMean.getResult();
    LOG.debug("average shape heightMean: " + heightMean);
    LOG.debug("average shape widthMean: " + widthMean);

    double minHeightBigShape = heightMean * 6;
    double minWidthWideShape = widthMean * 6;
    double minHeightWideShape = heightMean * 1.5;
    double minHeightTallShape = heightMean * 2.5;
    double maxWidthTallShape = widthMean / 2;
    LOG.debug("minHeightBigShape: " + minHeightBigShape);
    LOG.debug("minWidthWideShape: " + minWidthWideShape);
    LOG.debug("minHeightWideShape: " + minHeightWideShape);
    LOG.debug("minHeightTallShape: " + minHeightTallShape);
    LOG.debug("maxWidthTallShape: " + maxWidthTallShape);

    List<Shape> largeShapes = new ArrayList<Shape>();
    List<Shape> horizontalRules = new ArrayList<Shape>();
    for (Shape shape : shapes) {
        if (shape.getHeight() > minHeightBigShape) {
            LOG.debug("Removing " + shape + " (height)");
            largeShapes.add(shape);
        } else if (shape.getWidth() > minWidthWideShape && shape.getHeight() > minHeightWideShape) {
            // we don't want to remove horizontal bars, but we do want to remove other shapes.
            // why not? I suppose horizontal bars are easily represented as characters?
            LOG.debug("Removing " + shape + " (width)");
            largeShapes.add(shape);
        } else if (shape.getWidth() > minWidthWideShape) {
            // ok, we will remove horizontal rules after all
            LOG.debug("Removing " + shape + " (horizontal rule)");
            largeShapes.add(shape);
            horizontalRules.add(shape);
        } else if (shape.getWidth() <= maxWidthTallShape && shape.getHeight() > minHeightTallShape) {
            LOG.debug("Removing " + shape + " (narrow)");
            largeShapes.add(shape);
        }
    }

    // Only want to remove enclosed shapes if the large shape isn't a frame/grid
    // A) first reduce the shape by 5 percent and see it's cardinality reduces vastly (in which case it's a frame)
    // if so, don't remove enclosed shapes
    // B) next, detect white rectangles within the shape - if they're big enough, don't remove enclosed shapes      LOG.debug("Are large shapes frames or illustrations?");
    double maxFrameCardinalityRatio = 0.5;
    double minFrameWhiteAreaSizeRatio = 0.9;
    List<Shape> illustrations = new ArrayList<Shape>(largeShapes);
    for (Shape largeShape : largeShapes) {
        LOG.debug(largeShape.toString());
        int xOrigin = largeShape.getStartingPoint()[0] - largeShape.getLeft();
        int yOrigin = largeShape.getStartingPoint()[1] - largeShape.getTop();
        Shape dummyShape = graphicsService.getDot(sourceImage, xOrigin, yOrigin);
        // We want to fill up a mirror of the contiguous pixels within this shape,
        // which is what we'll use for further analysis to know
        // if it's a frame or not.
        WritableImageGrid mirror = graphicsService.getEmptyMirror(largeShape);
        this.findContiguousPixels(largeShape, mirror, dummyShape, xOrigin, yOrigin,
                sourceImage.getSeparationThreshold());

        int adjustedLeft = (int) Math.round((double) mirror.getWidth() * 0.05);
        int adjustedRight = (int) Math.round((double) mirror.getWidth() * 0.95);
        int adjustedTop = (int) Math.round((double) mirror.getHeight() * 0.05);
        int adjustedBottom = (int) Math.round((double) mirror.getHeight() * 0.95);

        int cardinality = 0;
        int innerCardinality = 0;
        for (int x = 0; x < mirror.getWidth(); x++) {
            for (int y = 0; y < mirror.getHeight(); y++) {
                if (mirror.getPixel(x, y) > 0) {
                    cardinality++;
                    if (x >= adjustedLeft && x <= adjustedRight && y >= adjustedTop && y <= adjustedBottom)
                        innerCardinality++;
                }
            }
        }

        LOG.debug("cardinality: " + cardinality);
        LOG.debug("innerCardinality: " + innerCardinality);
        double ratio = (double) innerCardinality / (double) cardinality;
        LOG.debug("ratio: " + ratio);
        if (ratio <= maxFrameCardinalityRatio) {
            LOG.debug("maxFrameCardinalityRatio: " + maxFrameCardinalityRatio);
            LOG.debug("Frame by cardinality! Removing from illustrations");
            illustrations.remove(largeShape);
        } else {
            // Now, it could still be a grid
            // to find this out we need to detect white areas inside the shape.
            WhiteAreaFinder whiteAreaFinder = new WhiteAreaFinder();
            double minWhiteAreaWidth = widthMean * 10;
            double minWhiteAreaHeight = heightMean * 4;
            List<Rectangle> whiteAreas = whiteAreaFinder.getWhiteAreas(mirror, 0, 0, 0, mirror.getWidth() - 1,
                    mirror.getHeight() - 1, minWhiteAreaWidth, minWhiteAreaHeight);
            int whiteAreaSize = 0;
            for (Rectangle whiteArea : whiteAreas) {
                whiteAreaSize += (whiteArea.getWidth() * whiteArea.getHeight());
            }

            int totalSize = mirror.getWidth() * mirror.getHeight();
            LOG.debug("whiteAreaSize: " + whiteAreaSize);
            LOG.debug("totalSize: " + totalSize);

            double sizeRatio = (double) whiteAreaSize / (double) totalSize;
            LOG.debug("sizeRatio: " + sizeRatio);

            if (sizeRatio >= minFrameWhiteAreaSizeRatio) {
                LOG.debug("minFrameWhiteAreaSizeRatio: " + minFrameWhiteAreaSizeRatio);
                LOG.debug("Frame by white area size! Removing from illustrations");
                illustrations.remove(largeShape);
            }

        }
    }

    for (Shape largeShape : illustrations) {
        // Add this to large shapes if it's not a "frame"
        // large shapes are used for paragraph detection
        sourceImage.getLargeShapes().add(largeShape);
    }

    // remove shapes that are enclosed inside illustrations
    List<Shape> enclosedShapesToDelete = new ArrayList<Shape>();
    int extension = 5;
    for (Shape shape : shapes) {
        for (Shape shapeToDelete : illustrations) {
            if (shape.getLeft() >= shapeToDelete.getLeft() - extension
                    && shape.getRight() <= shapeToDelete.getRight() + extension
                    && shape.getTop() >= shapeToDelete.getTop() - extension
                    && shape.getBottom() <= shapeToDelete.getBottom() + extension) {
                LOG.debug("Enclosed shape: " + shape);
                LOG.debug(" enclosed by " + shapeToDelete);
                enclosedShapesToDelete.add(shape);
            }
        }
    }

    shapes.removeAll(largeShapes);
    shapes.removeAll(enclosedShapesToDelete);

    // remove shapes that are practically touching horizontal rules (probably segments of the rule that got split)
    extension = 3;
    List<Shape> listToTestAgainst = horizontalRules;
    for (int i = 0; i < 3; i++) {
        List<Shape> horizontalRuleSegments = new ArrayList<Shape>();
        for (Shape horizontalRule : listToTestAgainst) {
            for (Shape shape : shapes) {
                if ((shape.getLeft() <= horizontalRule.getRight() + extension
                        || shape.getRight() >= horizontalRule.getLeft() - extension)
                        && shape.getTop() >= horizontalRule.getTop() - extension
                        && shape.getBottom() <= horizontalRule.getBottom() + extension) {
                    LOG.debug("Horizontal rule segment: " + shape);
                    LOG.debug(" touching " + horizontalRule);
                    horizontalRuleSegments.add(shape);
                    enclosedShapesToDelete.add(shape);
                }
            }
        }
        shapes.removeAll(horizontalRuleSegments);
        listToTestAgainst = horizontalRuleSegments;
        if (listToTestAgainst.size() == 0)
            break;
    }

}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static void drawFormAreas(int pageIndex, float densityThreshold, FormMaster master,
        PageTaskResult pageTaskResult, Graphics2D g, MarkRecognitionConfig markRecognizationConfig,
        DeskewedImageSource pageSource, int focusedColumnIndex, Rectangle scope) {
    int formAreaIndexInPage = 0;

    int minX = Integer.MAX_VALUE;
    int minY = Integer.MAX_VALUE;
    int maxX = Integer.MIN_VALUE;
    int maxY = Integer.MIN_VALUE;

    for (FormArea formArea : master.getFormAreaListByPageIndex(pageIndex)) {
        FormAreaResult result = (FormAreaResult) pageTaskResult.getPageAreaResultList()
                .get(formAreaIndexInPage);
        if (formArea.isMarkArea()) {
            if (focusedColumnIndex == formArea.getQuestionIndex()) {

                Rectangle rect = formArea.getRect();

                Point2D p1 = pageSource.getPoint((int) rect.getX(), (int) rect.getY());
                Point2D p2 = pageSource.getPoint((int) (rect.getX() + rect.getWidth()),
                        (int) (rect.getY() + rect.getHeight()));

                minX = Math.min(minX, (int) p1.getX());
                minY = Math.min(minY, (int) p1.getY());
                maxX = Math.max(maxX, (int) p2.getX());
                maxY = Math.max(maxY, (int) p2.getY());

                if (result.getDensity() < densityThreshold) {
                    g.setColor(FOCUSED_MARKED_COLOR);
                } else {
                    g.setColor(FOCUSED_NO_MARKED_COLOR);
                }/*w  w w. j  ava  2  s  .c o m*/

            } else {
                if (result.getDensity() < densityThreshold) {
                    g.setColor(MARKED_COLOR);
                } else {
                    g.setColor(NO_MARKED_COLOR);
                }
            }

            g.fillPolygon(pageSource.createRectPolygon(
                    getExtendedRectangle(formArea.getRect(), markRecognizationConfig.getHorizontalMargin(),
                            markRecognizationConfig.getVerticalMargin())));
            g.drawPolygon(pageSource.createRectPolygon(
                    getExtendedRectangle(formArea.getRect(), markRecognizationConfig.getHorizontalMargin() + 3,
                            markRecognizationConfig.getVerticalMargin() + 3)));

        } else {
            g.setColor(TEXTAREA_COLOR);
            g.fillPolygon(pageSource.createRectPolygon(formArea.getRect()));
        }
        formAreaIndexInPage++;
    }

    if (scope != null) {
        int borderMarginX = 20;
        int borderMarginY = 3;
        int margin = 40;

        int x = minX - borderMarginX;
        int y = minY - borderMarginY;
        int width = maxX - minX + borderMarginX * 2;
        int height = maxY - minY + borderMarginY * 2;

        scope.x = minX - margin;
        scope.y = minY - margin;
        scope.width = maxX - minX + margin * 2;
        scope.height = maxY - minY + margin * 2;

        Stroke stroke = new BasicStroke(4.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 2.0f,
                new float[] { 4.0f, 8.0f }, 0.0f);
        g.setStroke(stroke);
        g.setColor(FOCUSED_SCOPE_COLOR);
        g.drawRoundRect(x, y, width, height, 20, 20);
    }

}