Example usage for java.awt.geom Rectangle2D getWidth

List of usage examples for java.awt.geom Rectangle2D getWidth

Introduction

In this page you can find the example usage for java.awt.geom Rectangle2D getWidth.

Prototype

public abstract double getWidth();

Source Link

Document

Returns the width of the framing rectangle in double precision.

Usage

From source file:org.gumtree.vis.hist2d.Hist2DPanel.java

private void changeMaskYMin(double y) {
    Rectangle2D frame = getSelectedMask().getRectangleFrame();
    getSelectedMask().setRectangleFrame(new Rectangle2D.Double(frame.getMinX(), Math.min(frame.getMaxY(), y),
            frame.getWidth(), Math.abs(frame.getMaxY() - y)));
}

From source file:org.geoserver.wps.gs.download.DownloadProcessTest.java

/**
 * Test download of selected bands of raster data, scald and using a ROI area. 
 * Result contains only band 1.//from  w  w  w .j  a  v a 2s  . c  o  m
 * 
 * @throws Exception the exception
 */
@Test
public void testDownloadRasterSelectedBandsScaledWithROI() throws Exception {
    // Estimator process for checking limits
    DownloadEstimatorProcess limits = new DownloadEstimatorProcess(new StaticDownloadServiceConfiguration(),
            getGeoServer());
    final WPSResourceManager resourceManager = getResourceManager();
    // Creates the new process for the download
    DownloadProcess downloadProcess = new DownloadProcess(getGeoServer(), limits, resourceManager);

    ///////////////////////////////////////
    //      test full coverage           //
    ///////////////////////////////////////

    Polygon roi = (Polygon) new WKTReader2().read("POLYGON (( " + "-127.57473954542964 54.06575021619523, "
            + "-130.88669845369998 52.00807146727025, " + "-129.50812897394974 49.85372324691927, "
            + "-130.5300633861675 49.20465679591609, " + "-129.25955033314003 48.60392508062591, "
            + "-128.00975216684665 50.986137055052474, " + "-125.8623089087404 48.63154492960477, "
            + "-123.984159178178 50.68231871628503, " + "-126.91186316993704 52.15307567440926, "
            + "-125.3444367403868 53.54787804784162, " + "-127.57473954542964 54.06575021619523 " + "))");
    roi.setSRID(4326);

    // Download the coverage as tiff
    File rasterZip = downloadProcess.execute(getLayerId(MockData.USA_WORLDIMG), // layerName
            null, // filter
            "image/tiff", // outputFormat
            null, // targetCRS
            CRS.decode("EPSG:4326", true), // roiCRS
            roi, // roi
            false, // cropToGeometry
            null, // interpolation
            40, // targetSizeX
            40, // targetSizeY
            new int[] { 1 }, // bandSelectIndices
            new NullProgressListener() // progressListener
    );

    // Final checks on the result
    Assert.assertNotNull(rasterZip);
    GeoTiffReader reader = null;
    GridCoverage2D gc = null;
    try {
        final File[] tiffFiles = extractTIFFFile(rasterZip);
        Assert.assertNotNull(tiffFiles);
        Assert.assertTrue(tiffFiles.length > 0);
        reader = new GeoTiffReader(tiffFiles[0]);
        gc = reader.read(null);

        Assert.assertNotNull(gc);

        // check bands
        Assert.assertEquals(1, gc.getNumSampleDimensions());

        Rectangle2D originalGridRange = (GridEnvelope2D) reader.getOriginalGridRange();
        Assert.assertEquals(40, Math.round(originalGridRange.getWidth()));
        Assert.assertEquals(40, Math.round(originalGridRange.getHeight()));

        // check envelope
        Assert.assertEquals(-130.88669845369998, gc.getEnvelope().getLowerCorner().getOrdinate(0), 1E-6);
        Assert.assertEquals(48.611129008700004, gc.getEnvelope().getLowerCorner().getOrdinate(1), 1E-6);
        Assert.assertEquals(-123.95304462109999, gc.getEnvelope().getUpperCorner().getOrdinate(0), 1E-6);
        Assert.assertEquals(54.0861661371, gc.getEnvelope().getUpperCorner().getOrdinate(1), 1E-6);

    } finally {
        if (gc != null) {
            CoverageCleanerCallback.disposeCoverage(gc);
        }
        if (reader != null) {
            reader.dispose();
        }

        // clean up process
        resourceManager.finished(resourceManager.getExecutionId(true));
    }
}

From source file:net.sf.jasperreports.chartthemes.spring.EyeCandySixtiesChartTheme.java

@Override
public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,
        CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) {

    // check the value we are plotting...
    Number dataValue = dataset.getValue(row, column);
    if (dataValue == null) {
        return;//  w ww  .j av  a  2  s .com
    }

    double value = dataValue.doubleValue();

    Rectangle2D adjusted = new Rectangle2D.Double(dataArea.getX(), dataArea.getY() + getYOffset(),
            dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset());

    PlotOrientation orientation = plot.getOrientation();

    double barW0 = calculateBarW0(plot, orientation, adjusted, domainAxis, state, row, column);
    double[] barL0L1 = calculateBarL0L1(value);
    if (barL0L1 == null) {
        return; // the bar is not visible
    }

    RectangleEdge edge = plot.getRangeAxisEdge();
    double transL0 = rangeAxis.valueToJava2D(barL0L1[0], adjusted, edge);
    double transL1 = rangeAxis.valueToJava2D(barL0L1[1], adjusted, edge);
    double barL0 = Math.min(transL0, transL1);
    double barLength = Math.abs(transL1 - transL0);

    // draw the bar...
    Rectangle2D bar = null;
    if (orientation == PlotOrientation.HORIZONTAL) {
        bar = new Rectangle2D.Double(barL0, barW0, barLength, state.getBarWidth());
    } else {
        bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(), barLength);
    }
    Paint itemPaint = getItemPaint(row, column);
    if (itemPaint instanceof GradientPaint) {
        itemPaint = getGradientPaintTransformer().transform((GradientPaint) itemPaint, bar);
    }
    g2.setPaint(itemPaint);
    g2.fill(bar);

    double x0 = bar.getMinX();
    double x1 = x0 + getXOffset();
    double x2 = bar.getMaxX();
    double x3 = x2 + getXOffset();

    double y0 = bar.getMinY() - getYOffset();
    double y1 = bar.getMinY();
    double y2 = bar.getMaxY() - getYOffset();
    double y3 = bar.getMaxY();

    GeneralPath bar3dRight = null;
    GeneralPath bar3dTop = null;
    if (barLength > 0.0) {
        bar3dRight = new GeneralPath();
        bar3dRight.moveTo((float) x2, (float) y3);
        bar3dRight.lineTo((float) x2, (float) y1);
        bar3dRight.lineTo((float) x3, (float) y0);
        bar3dRight.lineTo((float) x3, (float) y2);
        bar3dRight.closePath();

        if (itemPaint instanceof Color) {
            g2.setPaint(((Color) itemPaint).darker());
        } else if (itemPaint instanceof GradientPaint) {
            GradientPaint gp = (GradientPaint) itemPaint;
            g2.setPaint(new StandardGradientPaintTransformer().transform(new GradientPaint(gp.getPoint1(),
                    gp.getColor1().darker(), gp.getPoint2(), gp.getColor2().darker(), gp.isCyclic()),
                    bar3dRight));
        }
        g2.fill(bar3dRight);
    }

    bar3dTop = new GeneralPath();
    bar3dTop.moveTo((float) x0, (float) y1);
    bar3dTop.lineTo((float) x1, (float) y0);
    bar3dTop.lineTo((float) x3, (float) y0);
    bar3dTop.lineTo((float) x2, (float) y1);
    bar3dTop.closePath();
    g2.fill(bar3dTop);

    if (isDrawBarOutline() && state.getBarWidth() > BAR_OUTLINE_WIDTH_THRESHOLD) {
        g2.setStroke(getItemOutlineStroke(row, column));
        g2.setPaint(getItemOutlinePaint(row, column));
        g2.draw(bar);
        if (bar3dRight != null) {
            g2.draw(bar3dRight);
        }
        if (bar3dTop != null) {
            g2.draw(bar3dTop);
        }
    }

    CategoryItemLabelGenerator generator = getItemLabelGenerator(row, column);
    if (generator != null && isItemLabelVisible(row, column)) {
        drawItemLabel(g2, dataset, row, column, plot, generator, bar, (value < 0.0));
    }

    // add an item entity, if this information is being collected
    EntityCollection entities = state.getEntityCollection();
    if (entities != null) {
        GeneralPath barOutline = new GeneralPath();
        barOutline.moveTo((float) x0, (float) y3);
        barOutline.lineTo((float) x0, (float) y1);
        barOutline.lineTo((float) x1, (float) y0);
        barOutline.lineTo((float) x3, (float) y0);
        barOutline.lineTo((float) x3, (float) y2);
        barOutline.lineTo((float) x2, (float) y3);
        barOutline.closePath();
        addItemEntity(entities, dataset, row, column, barOutline);
    }
}

From source file:org.squidy.designer.shape.ZoomShape.java

/**
 * @param goalDirectedZoom/* w  w  w.  j  av a  2  s  .  c om*/
 */
public ZoomShape(boolean goalDirectedZoom) {
    setBounds(Constants.DEFAULT_NODE_BOUNDS);

    if (goalDirectedZoom) {
        addInputEventListener(new PBasicInputEventHandler() {

            @Override
            public void mouseClicked(PInputEvent event) {
                if (!event.isHandled() && event.isLeftMouseButton() && event.getClickCount() == 2) {

                    PNode store = event.getPickedNode();
                    while (store != null && !(store instanceof IModelStore)) {
                        store = store.getParent();
                    }

                    PNode node = event.getPickedNode();
                    while (node != null && !(node instanceof ZoomShape<?>)) {
                        node = node.getParent();
                    }

                    if (node instanceof ZoomShape<?>) {

                        //                     if (LOG.isDebugEnabled()) {
                        //                         LOG.debug("Selected node to zoom is " + node + " and this is " + ZoomShape.this);
                        //                     }

                        node.moveToFront();

                        //                     PBounds boundsView = event.getCamera()
                        //                           .getViewBounds();
                        //                     PBounds boundsNode = ((ZoomShape<?>) node)
                        //                           .getGlobalBoundsZoomedIn();
                        //                     boolean sameNode = (Math.abs(boundsView.x
                        //                           - boundsNode.x) < 0.1 && Math
                        //                           .abs(boundsView.width - boundsNode.width) < 0.1)
                        //                           || (Math.abs(boundsView.y - boundsNode.y) < 0.1 && Math
                        //                                 .abs(boundsView.height
                        //                                       - boundsNode.height) < 0.1);
                        //
                        //                     if (!sameNode) {
                        if (store != null) {
                            ((IModelStore) store).getModel().setZoomedShape((ZoomShape<?>) node);
                            ((IModelStore) store).getModel().setZoomedBounds(getGlobalBoundsZoomedIn());
                        }
                        animateToCenterView(event.getCamera());
                        //                     }

                        event.setHandled(true);
                    }
                }
            }
        });
    }

    if (this instanceof Draggable) {
        addInputEventListener(new PDragEventHandler() {

            private PNode draggable;

            /*
             * (non-Javadoc)
             * 
             * @seeedu.umd.cs.piccolo.event.PDragEventHandler#
             * shouldStartDragInteraction
             * (edu.umd.cs.piccolo.event.PInputEvent)
             */
            @Override
            protected boolean shouldStartDragInteraction(PInputEvent event) {
                if (!event.isHandled()) {
                    PNode node = event.getPickedNode();
                    while (node != null && !(node instanceof Draggable)) {
                        node = node.getParent();
                    }
                    // Set dragged node to allow drag transformation.
                    draggable = node;
                    if (node instanceof Draggable) {
                        if (((Draggable) node).isDraggable() && super.shouldStartDragInteraction(event)) {
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }

            /*
             * (non-Javadoc)
             * 
             * @see
             * edu.umd.cs.piccolo.event.PDragEventHandler#drag(edu.umd.cs
             * .piccolo .event.PInputEvent)
             */
            @Override
            protected void drag(PInputEvent event) {
                if (!event.isHandled()) {
                    if (!event.getPath().acceptsNode(draggable)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Pick path doesn't accept node " + draggable.getClass().getName() + ".");
                        }
                        return;
                    }

                    PNode parent = draggable.getParent();

                    PDimension d = event.getDeltaRelativeTo(draggable);
                    draggable.localToParent(d);

                    PBounds parentBounds = parent.getBoundsReference();
                    Rectangle2D draggableBounds = draggable
                            .localToParent(draggable.getBounds().moveBy(d.getWidth(), d.getHeight()));

                    if (parentBounds.contains(draggableBounds)) {
                        draggable.offset(d.getWidth(), d.getHeight());
                    }

                    Point2D offset = draggable.getOffset();
                    if (offset.getX() < 0) {
                        draggable.setOffset(0, offset.getY());
                    }
                    if (offset.getY() < 0) {
                        draggable.setOffset(offset.getX(), 0);
                    }
                    if (offset.getX() > parentBounds.getWidth() - draggableBounds.getWidth()) {
                        draggable.setOffset(parentBounds.getWidth() - draggableBounds.getWidth(),
                                offset.getY());
                    }
                    if (offset.getY() > parentBounds.getHeight() - draggableBounds.getHeight()) {
                        draggable.setOffset(offset.getX(),
                                parentBounds.getHeight() - draggableBounds.getHeight());
                    }

                    event.setHandled(true);
                }

                // if (!event.isHandled()) {
                // if (!event.getPath().acceptsNode(draggable)) {
                // if (LOG.isDebugEnabled()) {
                // LOG.debug("Pick path doesn't accept node " +
                // draggable.getClass().getName() + ".");
                // }
                // return;
                // }
                //
                // Point2D current =
                // event.getPositionRelativeTo(ZoomShape.this);
                // draggable.localToParent(current);
                //                  
                // Point2D dest = new Point2D.Double();
                //                  
                // dest.setLocation((current.getX()), (current.getY()));
                //            
                // dest.setLocation(dest.getX() - (dest.getX() % 20),
                // dest.getY() - (dest.getY() % 20));
                //                  
                // // dest.setLocation(nodeStartPosition.getX() - (d.getX()
                // % 20), nodeStartPosition.getY() - (d.getY() % 20));
                //                  
                // System.out.println("OFFSET: " + dest);
                //                  
                // draggable.setOffset(dest.getX(), dest.getY());
                //
                // // }
                // event.setHandled(true);
                // }
            }
        });
    }

    MultiSelectionHandler multiSelectionHandler = new MultiSelectionHandler() {

        /* (non-Javadoc)
         * @see org.squidy.designer.event.MultiSelectionHandler#selectionAllowed(edu.umd.cs.piccolo.event.PInputEvent)
         */
        @Override
        protected boolean selectionAllowed(PInputEvent event) {
            PNode node = event.getPickedNode();
            return node instanceof Draggable && !((Draggable) node).isDraggable();
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * org.squidy.designer.event.MultiSelectionHandler#startSelection
         * (edu.umd.cs.piccolo.event.PInputEvent, java.awt.Shape)
         */
        @Override
        public void startSelection(PInputEvent event, Shape selectionShape) {
            if (!event.isHandled()) {
                multiSelection = selectionShape;

                event.setHandled(true);
                invalidatePaint();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * org.squidy.designer.event.MultiSelectionHandler#selection
         * (edu.umd.cs.piccolo.event.PInputEvent, java.awt.Shape)
         */
        @Override
        public void selection(PInputEvent event, Shape selectionShape) {
            if (!event.isHandled()) {
                multiSelection = selectionShape;

                event.setHandled(true);
                invalidatePaint();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * org.squidy.designer.event.MultiSelectionHandler#endSelection
         * (edu.umd.cs.piccolo.event.PInputEvent, java.awt.Shape)
         */
        @Override
        public void endSelection(PInputEvent event, Shape selectionShape) {
            if (!event.isHandled()) {
                multiSelection = null;

                for (Object o : getChildrenReference()) {
                    if (o instanceof VisualShape<?>) {
                        VisualShape<?> shape = (VisualShape<?>) o;

                        PBounds bounds = shape.getGlobalFullBounds();
                        if (selectionShape.contains(bounds)) {
                            System.out.println("containing: " + shape);
                        }
                    }
                }

                event.setHandled(true);
                invalidatePaint();
            }
        }
    };

    //       addInputEventListener(multiSelectionHandler);

    // Add knowledge base to zoom object if class is of type
    // <code>KnowledgeBased</code>.
    if (this instanceof NodeBased<?>) {
        boolean isWorkspace = this instanceof WorkspaceShape;

        knowledgeBase = new AdvancedKnowledgeBase<ZoomShape<VisualShape<?>>>(isWorkspace);

        addChild(knowledgeBase);
        knowledgeBase.setOffset(0, 895);
    }
}

From source file:extern.PlotBySplitClassRenderer.java

/**
 * Draws the visual representation of a single data item when the plot has
 * a vertical orientation.// ww w  .ja  v a 2  s.c  om
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param dataArea  the area within which the plot is being drawn.
 * @param plot  the plot (can be used to obtain standard color information
 *              etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset (must be an instance of
 *                 {@link BoxAndWhiskerCategoryDataset}).
 * @param row  the row index (zero-based).
 * @param column  the column index (zero-based).
 */
public void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
        CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row,
        int column) {

    if (lastSplitObj != column) {
        lastSplitObj = column;
        prevX = -1;
        prevY = -1;
    }

    BoxAndWhiskerCategoryDataset bawDataset = (BoxAndWhiskerCategoryDataset) dataset;

    double categoryEnd = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());
    double categoryStart = domainAxis.getCategoryStart(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());
    double categoryWidth = categoryEnd - categoryStart;

    double xx = categoryStart;
    int seriesCount = getRowCount();
    int categoryCount = getColumnCount();

    double widthToUse = Math.min(state.getBarWidth(), dataArea.getWidth() / 15);

    if (seriesCount > 1) {
        double seriesGap = dataArea.getWidth() * getItemMargin() / (categoryCount * (seriesCount - 1));
        double usedWidth = (widthToUse * seriesCount) + (seriesGap * (seriesCount - 1));
        // offset the start of the boxes if the total width used is smaller
        // than the category width
        double offset = (categoryWidth - usedWidth) / 2;
        xx = xx + offset + (row * (widthToUse + seriesGap));
    } else {
        // offset the start of the box if the box width is smaller than the
        // category width
        double offset = (categoryWidth - widthToUse) / 2;
        xx = xx + offset;
    }

    double yyAverage = 0.0;
    double yyOutlier;

    Paint itemPaint = getItemPaint(row, column);
    g2.setPaint(itemPaint);
    Stroke s = getItemStroke(row, column);
    g2.setStroke(s);

    double aRadius = 0; // average radius

    RectangleEdge location = plot.getRangeAxisEdge();

    Number yQ1 = bawDataset.getQ1Value(row, column);
    Number yQ3 = bawDataset.getQ3Value(row, column);
    Number yMax = bawDataset.getMaxRegularValue(row, column);
    Number yMin = bawDataset.getMinRegularValue(row, column);
    Shape box = null;

    double xxmid = xx + widthToUse / 2.0;
    double yyQ1 = 0;
    double yyQ3 = 0;

    if (yQ1 != null && yQ3 != null && yMax != null && yMin != null) {

        yyQ1 = rangeAxis.valueToJava2D(yQ1.doubleValue(), dataArea, location);
        yyQ3 = rangeAxis.valueToJava2D(yQ3.doubleValue(), dataArea, location);
        double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location);
        double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location);

        // draw the upper shadow...
        g2.draw(new Line2D.Double(xxmid, yyMax, xxmid, yyQ3));
        g2.draw(new Line2D.Double(xx, yyMax, xx + widthToUse, yyMax));

        // draw the lower shadow...
        g2.draw(new Line2D.Double(xxmid, yyMin, xxmid, yyQ1));
        g2.draw(new Line2D.Double(xx, yyMin, xx + widthToUse, yyMin));

        // draw the body...
        box = new Rectangle2D.Double(xx, Math.min(yyQ1, yyQ3), widthToUse, Math.abs(yyQ1 - yyQ3));
        if (this.fillBox) {
            g2.fill(box);
        }
        g2.setStroke(getItemOutlineStroke(row, column));
        g2.setPaint(getItemOutlinePaint(row, column));
        g2.draw(box);
    }

    g2.setPaint(this.artifactPaint);

    // draw mean - SPECIAL AIMS REQUIREMENT...
    Number yMean = bawDataset.getMeanValue(row, column);

    if (yMean != null && !Double.isNaN(yMean.doubleValue())) {
        yyAverage = rangeAxis.valueToJava2D(yMean.doubleValue(), dataArea, location);
        // THIS IS WHAT WE CHANGED
        //            aRadius = widthWeWannaUse / 4;
        aRadius = 4;
        // here we check that the average marker will in fact be visible
        // before drawing it...
        // WE HAD TO CHANGE THIS TOO I DON'T KNOW WHAT THEY WERE DOING
        if ((yyAverage > (dataArea.getMinY() - aRadius)) && (yyAverage < (dataArea.getMaxY() + aRadius))) {
            Ellipse2D.Double avgEllipse = new Ellipse2D.Double(xxmid - aRadius, yyAverage - aRadius,
                    aRadius * 2, aRadius * 2);

            //If this is a single point only, then draw this point with 
            //the color of its class.
            if (yQ1 != null && yQ3 != null) {
                if (aRadius / 2 > Math.abs(yyQ3 - yyQ1)) {
                    g2.setPaint(itemPaint);
                }
            }

            g2.fill(avgEllipse);
            g2.draw(avgEllipse);
        }
    }

    // draw median...
    Number yMedian = bawDataset.getMedianValue(row, column);

    if (yMedian != null && !Double.isNaN(yMedian.doubleValue())) {

        double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location);
        g2.draw(new Line2D.Double(xx, yyMedian, xx + widthToUse, yyMedian));

        // add a line to connect the means of the boxes
        if (prevX != -1 && prevY != -1) {
            g2.setPaint(artifactPaint);
            g2.draw(new Line2D.Double(prevX, prevY, xxmid, yyMedian));
        }
        prevX = xxmid;
        prevY = yyMedian;

    }

    // draw yOutliers...
    g2.setPaint(itemPaint);

    // draw outliers
    double oRadius = 4; // outlier radius
    List<Outlier> outliers = new ArrayList<Outlier>();

    // From outlier array sort out which are outliers and put these into a
    // list If there are any farouts, set the flag on the
    // OutlierListCollection
    List<Number> yOutliers = bawDataset.getOutliers(row, column);
    if (yOutliers != null) {
        for (int i = 0; i < yOutliers.size(); i++) {
            double outlier = yOutliers.get(i).doubleValue();

            yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location);
            outliers.add(new Outlier(xxmid, yyOutlier, oRadius));
        }

        // Process outliers. Each outlier is either added to the
        // appropriate outlier list or a new outlier list is made
        for (Outlier outlier : outliers) {
            Point2D point = outlier.getPoint();

            drawEllipse(point, oRadius, g2);
        }

    }

}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

@Override
public void drawString(final String s, final float x, float y) {
    if (s.length() == 0) {
        return;// w w  w .  java 2s  .com
    }
    setFillPaint();
    setStrokePaint();

    final AffineTransform at = getTransform();
    final AffineTransform at2 = getTransform();
    at2.translate(x, y);
    at2.concatenate(font.getTransform());
    setTransform(at2);
    final AffineTransform inverse = this.normalizeMatrix();
    final AffineTransform flipper = FLIP_TRANSFORM;
    inverse.concatenate(flipper);
    final double[] mx = new double[6];
    inverse.getMatrix(mx);
    cb.beginText();

    final float fontSize = font.getSize2D();
    if (lastBaseFont == null) {
        final String fontName = font.getName();
        final boolean bold = font.isBold();
        final boolean italic = font.isItalic();

        final BaseFontFontMetrics fontMetrics = metaData.getBaseFontFontMetrics(fontName, fontSize, bold,
                italic, null, metaData.isFeatureSupported(OutputProcessorFeature.EMBED_ALL_FONTS), false);
        final FontNativeContext nativeContext = fontMetrics.getNativeContext();
        lastBaseFont = fontMetrics.getBaseFont();

        cb.setFontAndSize(lastBaseFont, fontSize);
        if (fontMetrics.isTrueTypeFont() && bold && nativeContext.isNativeBold() == false) {
            final float strokeWidth = font.getSize2D() / 30.0f; // right from iText ...
            if (strokeWidth == 1) {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
            } else {
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                cb.setLineWidth(strokeWidth);
            }
        } else {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        }
    } else {
        cb.setFontAndSize(lastBaseFont, fontSize);
    }

    cb.setTextMatrix((float) mx[0], (float) mx[1], (float) mx[2], (float) mx[3], (float) mx[4], (float) mx[5]);
    double width = 0;
    if (fontSize > 0) {
        final float scale = 1000 / fontSize;
        final Font font = this.font.deriveFont(AffineTransform.getScaleInstance(scale, scale));
        final Rectangle2D stringBounds = font.getStringBounds(s, getFontRenderContext());
        width = stringBounds.getWidth() / scale;
    }
    if (s.length() > 1) {
        final float adv = ((float) width - lastBaseFont.getWidthPoint(s, fontSize)) / (s.length() - 1);
        cb.setCharacterSpacing(adv);
    }
    cb.showText(s);
    if (s.length() > 1) {
        cb.setCharacterSpacing(0);
    }
    cb.endText();
    setTransform(at);
    if (underline) {
        // These two are supposed to be taken from the .AFM file
        // int UnderlinePosition = -100;
        final int UnderlineThickness = 50;
        //
        final double d = PdfGraphics2D.asPoints(UnderlineThickness, (int) fontSize);
        setStroke(new BasicStroke((float) d));
        y = (float) ((y) + PdfGraphics2D.asPoints((UnderlineThickness), (int) fontSize));
        final Line2D line = new Line2D.Double(x, y, (width + x), y);
        draw(line);
    }
}

From source file:gov.nih.nci.caintegrator.application.graphing.BoxAndWhiskerDotsRenderer.java

/**
 * Draws the visual representation of a single data item when the plot has 
 * a vertical orientation./*from w w  w  .  jav  a  2s.c  om*/
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param dataArea  the area within which the plot is being drawn.
 * @param plot  the plot (can be used to obtain standard color information 
 *              etc).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param row  the row index (zero-based).
 * @param column  the column index (zero-based).
 */
public void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea,
        CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row,
        int column) {

    BoxAndWhiskerCategoryDataset bawDataset = (BoxAndWhiskerCategoryDataset) dataset;

    double categoryEnd = domainAxis.getCategoryEnd(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());
    double categoryStart = domainAxis.getCategoryStart(column, getColumnCount(), dataArea,
            plot.getDomainAxisEdge());

    double categoryWidth = (categoryEnd - categoryStart);

    double xx = categoryStart;
    int seriesCount = getRowCount();
    int categoryCount = getColumnCount();

    if (seriesCount > 1) {
        double seriesGap = dataArea.getWidth() * getItemMargin() / (categoryCount * (seriesCount - 1));
        double usedWidth = (state.getBarWidth() * seriesCount) + (seriesGap * (seriesCount - 1));
        // offset the start of the boxes if the total width used is smaller
        // than the category width
        double offset = (categoryWidth - usedWidth) / 2;
        xx = xx + offset + (row * (state.getBarWidth() + seriesGap));
    } else {
        // offset the start of the box if the box width is smaller than the 
        // category width
        double offset = (categoryWidth - state.getBarWidth()) / 2;
        xx = xx + offset;
    }

    double yyAverage = 0.0;
    double yyOutlier;

    //bar colors are determined by the Paint p obtained here in a rotational
    //manner (from a Color array).  By switching the column and raw values,
    //you can get a different color pattern for the bar:  In the method 
    //getItemPaint(), only the first argument counts for the color. The original
    //code Paint p = getItemPaint(row, column); is commented out for a difference.
    //Paint p = getItemPaint(row, column);
    Paint p = getItemPaint(column, row); // <-- this is wrong, dont know who put this here
    // Paint p = PaintUtilities.stringToColor("red"); // coin plot should all be one color
    if (p != null) {
        g2.setPaint(p);
    }
    Stroke s = getItemStroke(row, column);
    g2.setStroke(s);

    double aRadius = 0; // average radius

    RectangleEdge location = plot.getRangeAxisEdge();

    Number yQ1 = bawDataset.getQ1Value(row, column);
    Number yQ3 = bawDataset.getQ3Value(row, column);
    Number yMax = bawDataset.getMaxRegularValue(row, column);
    Number yMin = bawDataset.getMinRegularValue(row, column);
    Shape box = null;
    if (yQ1 != null && yQ3 != null && yMax != null && yMin != null) {

        double yyQ1 = rangeAxis.valueToJava2D(yQ1.doubleValue(), dataArea, location);
        double yyQ3 = rangeAxis.valueToJava2D(yQ3.doubleValue(), dataArea, location);
        double yyMax = rangeAxis.valueToJava2D(yMax.doubleValue(), dataArea, location);
        double yyMin = rangeAxis.valueToJava2D(yMin.doubleValue(), dataArea, location);
        double xxmid = xx + state.getBarWidth() / 2.0;

        // draw the upper shadow...
        g2.draw(new Line2D.Double(xxmid, yyMax, xxmid, yyQ3));
        g2.draw(new Line2D.Double(xx, yyMax, xx + state.getBarWidth(), yyMax));

        // draw the lower shadow...
        g2.draw(new Line2D.Double(xxmid, yyMin, xxmid, yyQ1));
        g2.draw(new Line2D.Double(xx, yyMin, xx + state.getBarWidth(), yyMin));

        // draw the body...
        box = new Rectangle2D.Double(xx, Math.min(yyQ1, yyQ3), state.getBarWidth(), Math.abs(yyQ1 - yyQ3));
        if (this.fillBox) {
            g2.fill(box);
        }
        //The following draw the boxes where mean and media are located.
        g2.draw(box);

    }

    g2.setPaint(this.artifactPaint);

    // draw median...
    Number yMedian = bawDataset.getMedianValue(row, column);
    if (yMedian != null) {
        double yyMedian = rangeAxis.valueToJava2D(yMedian.doubleValue(), dataArea, location);
        g2.draw(new Line2D.Double(xx, yyMedian, xx + state.getBarWidth(), yyMedian));
    }

    //caIntegrator:  The outLiner is no longer needed to be here.
    // draw the rawData around the box...
    /////////////////////////////////caIntegrator: Begin of drawing dots around the box
    double maxAxisValue = rangeAxis.valueToJava2D(rangeAxis.getUpperBound(), dataArea, location) + aRadius;
    double minAxisValue = rangeAxis.valueToJava2D(rangeAxis.getLowerBound(), dataArea, location) - aRadius;

    g2.setPaint(p);

    //caIntegrator: oRadius is the radius of the outlier circles. It was used to be 3.
    double oRadius = state.getBarWidth() / 10; // outlier radius

    List outliers = new ArrayList();

    //Get the raw item data for a given row/column pair for plotting.
    //getRawItemData() method is added to bawDataset object for 
    //this purpose.

    //List yOutliers = bawDataset.getRawItemData(row, column);
    List yOutliers = this.caintegOutliers.get(String.valueOf(row) + "_" + String.valueOf(column));

    if (yOutliers != null) {
        for (int i = 0; i < yOutliers.size(); i++) {
            double outlier = ((Number) yOutliers.get(i)).doubleValue();
            yyOutlier = rangeAxis.valueToJava2D(outlier, dataArea, location);
            outliers.add(new Outlier(xx + state.getBarWidth() / 2.0, yyOutlier, oRadius));

            Collections.sort(outliers);
        }

        //Sort the raw data according to its Y axis first as groups.
        //Grouping of these raw data is based on a single standard:
        //if any number of data, when plotted on a vertical line, overlap
        //with one another, they belong to the same group. In this case, 
        //the grouping is largely determined by the diameter of the dot, that
        //represents each raw data.
        boolean firstOutlier = true;
        double topY = 0;
        double bottomY = 0;
        List groupList = new ArrayList();
        List tempList = null;
        double diameter = 2 * oRadius;

        double difference = 0;
        for (Iterator iterator = outliers.iterator(); iterator.hasNext();) {

            Outlier outlier = (Outlier) iterator.next();

            //Set the smallest outlier as the base bottom line
            if (firstOutlier) {
                firstOutlier = false;
                bottomY = outlier.getY();
                tempList = new ArrayList();
                tempList.add(outlier);
                continue;
            }

            topY = outlier.getY();

            //If this one and the one before it is overlapping,
            //Then put them in the same group, so we can spread them
            //horizontally
            difference = topY - bottomY;

            if (difference < diameter) {
                tempList.add(outlier);
            }
            //They do not overlap, they belong to the different groups.
            else {
                bottomY = topY;
                groupList.add(tempList);
                tempList = new ArrayList();
                tempList.add(outlier);
            }
        }

        //caIntegrator - x axis cloud
        //Process each outlier's x coordinates  
        boolean isOdd = true;
        double offSet = 0;
        int listSize = 0;

        for (int m = 0; m < groupList.size(); m++) {
            List list = (List) groupList.get(m);
            if (list != null && list.size() > 1) {
                listSize = list.size();
                isOdd = (listSize % 2 == 1) ? true : false;

                if (isOdd) {
                    offSet = diameter * (listSize / 2);
                } else {
                    offSet = diameter * (listSize / 2) - oRadius;
                }

                Random r = new Random();
                offSet = (Math.abs(r.nextInt()) % 3) * 3;
                offSet = 0;

                for (int n = 0; n < list.size(); n++) {
                    Outlier outlier = (Outlier) list.get(n);

                    outlier.setPoint(new Point2D.Double(outlier.getX() - offSet, outlier.getY()));
                    offSet = offSet - diameter;
                    r = new Random();
                    int randInt = Math.abs(r.nextInt()) % 3;
                    offSet = randInt * 2;
                }
            }
        }

        //Draw these dots on the graph.         
        for (Iterator iterator = groupList.iterator(); iterator.hasNext();) {

            List list = (List) iterator.next();
            for (int i = 0; i < list.size(); i++) {
                Outlier outlier = (Outlier) list.get(i);
                Point2D point = outlier.getPoint();
                drawEllipse(point, oRadius, g2);
            }
        }
    }
}

From source file:savant.view.swing.GraphPane.java

/**
 * Render the background of this GraphPane
 *
 * @param g The graphics object to use/*from   w ww .ja  v a 2  s  .  c  o m*/
 */
private void renderBackground(Graphics2D g2, boolean xGridOn, boolean yGridOn) {
    int h = getHeight();
    int w = getWidth();

    // Paint a gradient from top to bottom
    GradientPaint gp0 = new GradientPaint(0, 0, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_TOP), 0,
            h, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_BOTTOM));
    g2.setPaint(gp0);
    g2.fillRect(0, 0, w, h);

    // We don't want the axes stomping on our labels, so make sure the clip excludes them.
    Area clipArea = new Area(new Rectangle(0, 0, w, h));
    Color gridColor = ColourSettings.getColor(ColourKey.AXIS_GRID);

    if (yGridOn) {
        // Smallish font for tick labels.
        Font tickFont = g2.getFont().deriveFont(Font.PLAIN, 9);

        int[] yTicks = MiscUtils.getTickPositions(transformYPixel(getHeight()), transformYPixel(0.0));

        g2.setColor(gridColor);
        g2.setFont(tickFont);
        for (int t : yTicks) {
            double y = transformYPos(t);

            // Skip labels at the top or bottom of the window because they look stupid.
            if (y != 0.0 && y != getHeight()) {
                String s = Integer.toString(t);
                Rectangle2D labelRect = tickFont.getStringBounds(s, g2.getFontRenderContext());
                double baseline = y + labelRect.getHeight() * 0.5 - 2.0;
                g2.drawString(s, 4.0F, (float) baseline);
                clipArea.subtract(new Area(new Rectangle2D.Double(3.0, baseline - labelRect.getHeight() - 1.0,
                        labelRect.getWidth() + 2.0, labelRect.getHeight() + 2.0)));
            }
        }
        g2.setClip(clipArea);
        for (int t2 : yTicks) {
            double y = transformYPos(t2);
            g2.draw(new Line2D.Double(0.0, y, w, y));
        }
    }
    if (xGridOn) {
        Range r = LocationController.getInstance().getRange();
        int[] xTicks = MiscUtils.getTickPositions(r);

        g2.setColor(gridColor);
        for (int t : xTicks) {
            double x = transformXPos(t);
            g2.draw(new Line2D.Double(x, 0, x, h));
        }
    }
    g2.setClip(null);
}

From source file:org.photovault.imginfo.PhotoInfo.java

@Transient
public Dimension getCroppedSize() {
    double rot = processing.getRotation() * Math.PI / 180.0;
    double origWidth = original.getWidth();
    double origHeight = original.getHeight();
    double rotSin = Math.abs(Math.sin(rot));
    double rotCos = Math.abs(Math.cos(rot));
    double rotWidth = origWidth * rotCos + origHeight * rotSin;
    double rotHeight = origWidth * rotSin + origHeight * rotCos;
    Rectangle2D crop = processing.getCropping();
    Dimension ret = new Dimension((int) (rotWidth * crop.getWidth()), (int) (rotHeight * crop.getHeight()));
    return ret;/*  w  w  w  .  j  a  va 2s.c om*/
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * Draws the object.// w ww.  j  av a 2s .co  m
 *
 * @param graphics
 *          the graphics device.
 * @param area
 *          the area inside which the object should be drawn.
 */
public void draw(final Graphics2D graphics, final Rectangle2D area) {
    final Graphics2D g2 = (Graphics2D) graphics.create();
    if (isDrawPageBackground()) {
        g2.setPaint(Color.white);
        g2.fill(area);
    }
    g2.translate(-area.getX(), -area.getY());

    try {
        final StrictBounds pageBounds = StrictGeomUtility.createBounds(area.getX(), area.getY(),
                area.getWidth(), area.getHeight());
        this.pageArea = pageBounds;
        this.drawArea = pageBounds;
        this.graphics = g2;

        if (startBlockBox(rootBox)) {
            processRootBand(pageBounds);
        }
        finishBlockBox(rootBox);
    } finally {
        this.graphics = null;
        this.drawArea = null;
        g2.dispose();
    }
}