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(Point p, Dimension d) 

Source Link

Document

Constructs a new Rectangle whose upper-left corner is specified by the Point argument, and whose width and height are specified by the Dimension argument.

Usage

From source file:ch.rgw.tools.StringTool.java

/**
 * return the bounds of a Rectangle around a String
 * /*from  w  w  w. jav a2s  .c  o  m*/
 * @deprecated this ist a dependency to Swing
 */
@Deprecated
public static Rectangle2D getStringBounds(final String s, final Graphics g) {
    if (isNothing(s)) {
        return new Rectangle(0, 0);
    }
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    Font fnt = g.getFont();
    Rectangle2D r = fnt.getStringBounds(s, frc);
    return r;
}

From source file:io.github.mzmine.util.jfreechart.JFreeChartUtils.java

public static void exportToImageFile(ChartViewer chartNode, File file, ImgFileType fileType) {

    final JFreeChart chart = chartNode.getChart();
    final int width = (int) chartNode.getWidth();
    final int height = (int) chartNode.getHeight();

    try {/*from ww  w .  j a v a  2s .c o m*/

        switch (fileType) {

        case JPG:
            ExportUtils.writeAsJPEG(chart, width, height, file);
            break;

        case PNG:
            ExportUtils.writeAsPNG(chart, width, height, file);
            break;

        case SVG:
            setDrawSeriesLineAsPath(chart, true);
            ExportUtils.writeAsSVG(chart, width, height, file);
            setDrawSeriesLineAsPath(chart, false);
            break;

        case PDF:
            setDrawSeriesLineAsPath(chart, true);
            ExportUtils.writeAsPDF(chart, width, height, file);
            setDrawSeriesLineAsPath(chart, false);
            break;

        case EMF:
            FileOutputStream out2 = new FileOutputStream(file);
            setDrawSeriesLineAsPath(chart, true);
            EMFGraphics2D g2d2 = new EMFGraphics2D(out2, new Dimension(width, height));
            g2d2.startExport();
            chart.draw(g2d2, new Rectangle(width, height));
            g2d2.endExport();
            setDrawSeriesLineAsPath(chart, false);
            break;

        case EPS:
            FileOutputStream out = new FileOutputStream(file);
            setDrawSeriesLineAsPath(chart, true);
            EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
            g2d.setGraphicContext(new GraphicContext());
            g2d.setupDocument(out, width, height);
            chart.draw(g2d, new Rectangle(width, height));
            g2d.finish();
            setDrawSeriesLineAsPath(chart, false);
            out.close();
            break;

        }

    } catch (IOException e) {
        MZmineGUI.displayMessage("Unable to save image: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.hmsinc.epicenter.spatial.render.SpatialScanRenderer.java

/**
 * @param context/*  w  w  w  . j  av  a2  s.  c om*/
 * @return
 */
private BufferedImage renderImage(final MapContext context, int width, int height) {

    logger.trace("Image width: {}  height: {}", width, height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D graphics2D = (Graphics2D) image.getGraphics();

    final GTRenderer renderer = new StreamingRenderer();
    final RenderingHints h = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    h.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    h.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    h.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    h.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    renderer.setJava2DHints(h);
    renderer.setContext(context);
    renderer.paint(graphics2D, new Rectangle(width, height), context.getAreaOfInterest());

    return image;
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

/**
 * Render the pie chart with the given height
 * // w w w  .  j  a va2  s  .c  o  m
 * @param height
 *          The height of the resulting image
 * @return The pie chart rendered as an image
 */
public BufferedImage render(int height) {
    BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.scale(zoom, zoom);
    // fill background to white
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(totalWidth, totalHeight));
    // prepare render hints
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // draw shadow image
    g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver());

    double start = 0;
    List<Arc2D> pies = new ArrayList<>();
    // pie segmente erzeugen und fuellen
    if (total == 0) {
        g2.setColor(BRIGHT_GRAY);
        g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
        g2.setColor(Color.WHITE);
        g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
    } else {
        for (Segment s : segments) {
            double portionDegrees = s.getPortion() / total;
            Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor());
            if (withSubSegments) {
                double smallRadius = radius * s.getSubSegmentRatio();
                paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker());
            }
            start += portionDegrees;
            // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen)
            String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0);
            p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25")
            s.setPercent(p + "%");
            pies.add(pie);
        }
        // weissen Rahmen um die pie segmente zeichen
        g2.setColor(Color.WHITE);
        for (Arc2D pie : pies) {
            g2.draw(pie);
        }
    }
    // Legende zeichnen
    renderLegend(g2);
    // "xx%" Label direkt auf die pie segmente zeichen
    g2.setColor(Color.WHITE);
    float fontSize = 32f;
    g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD));
    start = 0;
    for (Segment s : segments) {
        if (s.getPortion() < 1E-6) {
            continue; // ignore segments with portions that are extremely small
        }
        double portionDegrees = s.getPortion() / total;
        double angle = start + portionDegrees / 2; // genau in der Mitte des Segments
        double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char
        int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt);
        int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2);
        g2.drawString(s.getPercent(), x, y);
        start += portionDegrees;
    }
    return image;
}

From source file:com.wattzap.view.graphs.SCHRGraph.java

public SCHRGraph(ArrayList<Telemetry> telemetry[]) {
    super();//ww w.  j a v a2 s .c o  m
    this.telemetry = telemetry;

    final NumberAxis domainAxis = new NumberAxis("Time (h:m:s)");

    domainAxis.setVerticalTickLabels(true);
    domainAxis.setTickLabelPaint(Color.black);
    domainAxis.setAutoRange(true);

    domainAxis.setNumberFormatOverride(new NumberFormat() {
        @Override
        public StringBuffer format(double millis, StringBuffer toAppendTo, FieldPosition pos) {
            if (millis >= 3600000) {
                // hours, minutes and seconds
                return new StringBuffer(

                        String.format("%d:%d:%d", TimeUnit.MILLISECONDS.toHours((long) millis),
                                TimeUnit.MILLISECONDS.toMinutes(
                                        (long) millis - TimeUnit.MILLISECONDS.toHours((long) millis) * 3600000),
                                TimeUnit.MILLISECONDS.toSeconds((long) millis) - TimeUnit.MINUTES
                                        .toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis))));
            } else if (millis >= 60000) {
                // minutes and seconds
                return new StringBuffer(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes((long) millis),
                        TimeUnit.MILLISECONDS.toSeconds((long) millis)
                                - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis))));
            } else {
                return new StringBuffer(String.format("%d", TimeUnit.MILLISECONDS.toSeconds((long) millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) millis))));
            }
        }

        @Override
        public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
            return new StringBuffer(String.format("%s", number));
        }

        @Override
        public Number parse(String source, ParsePosition parsePosition) {
            return null;
        }
    });

    // create plot ...
    final XYItemRenderer powerRenderer = new StandardXYItemRenderer() {
        Stroke regularStroke = new BasicStroke(0.7f);
        Color color;

        public void setColor(Color color) {
            this.color = color;
        }

        @Override
        public Stroke getItemStroke(int row, int column) {
            return regularStroke;
        }

        @Override
        public Paint getItemPaint(int row, int column) {
            return orange;
        }
    };
    powerRenderer.setSeriesPaint(0, orange);
    plot = new XYPlot();
    plot.setRenderer(0, powerRenderer);
    plot.setRangeAxis(0, powerAxis);
    plot.setDomainAxis(domainAxis);

    // add a second dataset and renderer...
    final XYItemRenderer cadenceRenderer = new StandardXYItemRenderer() {
        Stroke regularStroke = new BasicStroke(0.7f);
        Color color;

        public void setColor(Color color) {
            this.color = color;
        }

        @Override
        public Stroke getItemStroke(int row, int column) {
            return regularStroke;
        }

        @Override
        public Paint getItemPaint(int row, int column) {
            return cornflower;
        }

        public Shape lookupLegendShape(int series) {
            return new Rectangle(15, 15);
        }
    };

    final ValueAxis cadenceAxis = new NumberAxis(userPrefs.messages.getString("cDrpm"));
    cadenceAxis.setRange(0, 200);

    // arguments of new XYLineAndShapeRenderer are to activate or deactivate
    // the display of points or line. Set first argument to true if you want
    // to draw lines between the points for e.g.
    plot.setRenderer(1, cadenceRenderer);
    plot.setRangeAxis(1, cadenceAxis);
    plot.mapDatasetToRangeAxis(1, 1);
    cadenceRenderer.setSeriesPaint(0, cornflower);

    // add a third dataset and renderer...
    final XYItemRenderer hrRenderer = new StandardXYItemRenderer() {
        Stroke regularStroke = new BasicStroke(0.7f);
        Color color;

        public void setColor(Color color) {
            this.color = color;
        }

        @Override
        public Stroke getItemStroke(int row, int column) {
            return regularStroke;
        }

        @Override
        public Paint getItemPaint(int row, int column) {
            return straw;
        }

    };

    // arguments of new XYLineAndShapeRenderer are to activate or deactivate
    // the display of points or line. Set first argument to true if you want
    // to draw lines between the points for e.g.
    final ValueAxis heartRateAxis = new NumberAxis(userPrefs.messages.getString("hrBpm"));
    heartRateAxis.setRange(0, 200);

    plot.setRenderer(2, hrRenderer);
    hrRenderer.setSeriesPaint(0, straw);

    plot.setRangeAxis(2, heartRateAxis);
    plot.mapDatasetToRangeAxis(2, 2);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    plot.setBackgroundPaint(Color.DARK_GRAY);
    // return a new chart containing the overlaid plot...
    JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    chart.getLegend().setBackgroundPaint(Color.gray);

    chartPanel = new ChartPanel(chart);

    // TODO: maybe remember sizes set by user?
    this.setPreferredSize(new Dimension(1200, 500));
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.setBackground(Color.gray);

    setLayout(new BorderLayout());
    add(chartPanel, BorderLayout.CENTER);

    SmoothingPanel smoothingPanel = new SmoothingPanel(this);
    add(smoothingPanel, BorderLayout.SOUTH);

    //infoPanel = new InfoPanel();
    //add(infoPanel, BorderLayout.NORTH);
    setVisible(true);
}

From source file:edu.jhuapl.graphs.controller.GraphObject.java

public void writeChartAsEPS(OutputStream out, int graphWidth, int graphHeight) throws IOException {
    EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
    g2d.setGraphicContext(new GraphicContext());
    g2d.setupDocument(out, graphWidth, graphHeight);
    graphSource.getChart().draw(g2d, new Rectangle(graphWidth, graphHeight));
    g2d.finish();/*w w w  .  j a  v  a2s. c  om*/
}

From source file:com.alvermont.terraj.util.io.ImagePrinter.java

/**
 * Render an image for printing.//from   ww w .j a va2  s .c  om
 *
 * @param graphics The graphics context to print on
 * @param pageFormat The page format being used
 * @param pageIndex The page being printed
 * @throws java.awt.print.PrinterException If there is an error in printing
 * @return An indication of the result of page rendering for this page
 */
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    final Graphics2D g2 = (Graphics2D) graphics;

    // we only expect to be printing 1 page as the image is scaled
    if (pageIndex >= 1) {
        return Printable.NO_SUCH_PAGE;
    }

    // translate the coordinate system to match up the image with 
    // the printable area
    g2.translate(getFormat().getImageableX(), pageFormat.getImageableY());

    final Rectangle componentBounds = new Rectangle(getImage().getWidth(), getImage().getHeight());
    g2.translate(-componentBounds.x, -componentBounds.y);

    // scale the image to fit
    scaleToFit(true);
    g2.scale(getScaleX(), getScaleY());

    // render the image
    g2.drawImage(getImage(), null, 0, 0);

    // done
    return Printable.PAGE_EXISTS;
}

From source file:edu.jhuapl.graphs.controller.GraphObject.java

public void writeChartAsEMF(OutputStream out, int graphWidth, int graphHeight) throws IOException {
    EMFGraphics2D g2d = new EMFGraphics2D(out, new Dimension(graphWidth, graphHeight));
    g2d.startExport();//from   ww w.ja va2 s  . c o m
    graphSource.getChart().draw((Graphics2D) g2d.create(), new Rectangle(graphWidth, graphHeight));
    g2d.endExport();
    g2d.closeStream();
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.controls.DendogramView.java

/**
 * @param t//from   w  ww .j  ava2s .  c o  m
 * @param numClusters
 * @return
 */
private VisualizationViewer generateGraph(ClusteringTree t, final int numClusters) {

    DelegateTree<ChildDG, EdgeDG> g = new DelegateTree<ChildDG, EdgeDG>();

    ClusterNode root = t.findNode(1);

    mMergeCostMax = null;
    mMergeCostMin = null;
    mMergeCostSumMax = null;
    mMergeCostSumMin = null;

    calcMergeCostSum(root, root.getMergeCost(), numClusters);

    findMinMaxMergeCost(root, true, numClusters);

    nodeId = 0;
    ChildDG rc = new ChildDG(root);

    addChildren(root, g, rc, numClusters);
    Layout<ChildDG, EdgeDG> layout = new TreeLayout<ChildDG, EdgeDG>(g);

    VisualizationViewer<ChildDG, EdgeDG> graphComponent = new VisualizationViewer<ChildDG, EdgeDG>(layout);
    DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
    gm.setMode(ModalGraphMouse.Mode.TRANSFORMING);
    graphComponent.setGraphMouse(gm);

    graphComponent.enableInputMethods(true);

    RenderContext<ChildDG, EdgeDG> c = graphComponent.getRenderContext();
    graphComponent.setVertexToolTipTransformer(new Transformer<ChildDG, String>() {

        @Override
        public String transform(ChildDG c) {
            if (c.getNode().getMergeCost() == null) {
                return "count:" + c.getNode().getNodes().length + " " + c.getTooltip();
            } else {
                return "merge cotst:" + c.getNode().getMergeCost() + " count:" + c.getNode().getNodes().length
                        + " " + c.getTooltip();
            }
        }
    });

    graphComponent.setSize(frame.getContentPane().getWidth(),
            frame.getContentPane().getHeight() - clusterPanel.getHeight());

    // change edge-stroke-thickness
    c.setEdgeStrokeTransformer(new Transformer<EdgeDG, Stroke>() {

        @Override
        public Stroke transform(EdgeDG _arg0) {
            return new BasicStroke(_arg0.getMergeCost().floatValue() * MAX_STROKE_WIDTH);
        }
    });
    final Rectangle fake = new Rectangle(1, 1);
    c.setEdgeArrowTransformer(new Transformer<Context<Graph<ChildDG, EdgeDG>, EdgeDG>, Shape>() {

        @Override
        public Shape transform(Context<Graph<ChildDG, EdgeDG>, EdgeDG> _arg0) {
            return fake;
        }
    });
    // change vertex-fill-color
    c.setVertexFillPaintTransformer(new Transformer<ChildDG, Paint>() {

        @Override
        public Paint transform(ChildDG _arg0) {
            if (_arg0.getPaint() == null) {
                if (_arg0.getMergeCostSum() != null) {
                    double normalized = getNormalizedValue(_arg0.getMergeCostSum(), mMergeCostSumMax,
                            mMergeCostSumMin, _arg0.getMergeCostSum());
                    int cc = (int) Math.round(normalized * (palette.getColors().length - 1));
                    return palette.getColor(cc);
                } else {
                    return palette.getColor(palette.getColors().length - 1);
                }
            } else {
                return _arg0.getPaint();
            }
        }
    });

    return graphComponent;
}

From source file:com.orsonpdf.demo.PDFTimeSeriesChartDemo1.java

/**
 * Starting point for the demo./*from w  ww. j a v a 2 s .  c  o  m*/
 * 
 * @param args  ignored.
 * 
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    JFreeChart chart = createChart(createDataset());
    PDFDocument pdfDoc = new PDFDocument();
    pdfDoc.setTitle("PDFTimeSeriesChartDemo1");
    pdfDoc.setAuthor("Object Refinery Limited");
    Page page = pdfDoc.createPage(new Rectangle(612, 468));
    PDFGraphics2D g2 = page.getGraphics2D();
    g2.setRenderingHint(PDFHints.KEY_DRAW_STRING_TYPE, PDFHints.VALUE_DRAW_STRING_TYPE_VECTOR);
    chart.draw(g2, new Rectangle(0, 0, 612, 468));
    File f = new File("PDFTimeSeriesChartDemo1.pdf");
    pdfDoc.writeToFile(f);
}