Example usage for java.awt Graphics2D create

List of usage examples for java.awt Graphics2D create

Introduction

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

Prototype

public abstract Graphics create();

Source Link

Document

Creates a new Graphics object that is a copy of this Graphics object.

Usage

From source file:image.writer.ImageWriterExample1.java

/**
 * Paints a few things on a Graphics2D instance.
 * @param g2d the Graphics2D instance/*from  w  w w .  j  a  v  a 2 s  .  c  o  m*/
 * @param pageNum a page number
 */
protected void paintSome(Graphics2D g2d, int pageNum) {
    //Paint a bounding box
    g2d.drawRect(0, 0, 400, 200);

    //A few rectangles rotated and with different color
    Graphics2D copy = (Graphics2D) g2d.create();
    int c = 12;
    for (int i = 0; i < c; i++) {
        float f = ((i + 1) / (float) c);
        Color col = new Color(0.0f, 1 - f, 0.0f);
        copy.setColor(col);
        copy.fillRect(70, 90, 50, 50);
        copy.rotate(-2 * Math.PI / (double) c, 70, 90);
    }
    copy.dispose();

    //Some text
    copy = (Graphics2D) g2d.create();
    copy.rotate(-0.25);
    copy.setColor(Color.RED);
    copy.setFont(new Font("sans-serif", Font.PLAIN, 36));
    copy.drawString("Hello world!", 140, 140);
    copy.setColor(Color.RED.darker());
    copy.setFont(new Font("serif", Font.PLAIN, 36));
    copy.drawString("Hello world!", 140, 180);
    copy.dispose();

    //Try attributed text
    AttributedString aString = new AttributedString("This is attributed text.");
    aString.addAttribute(TextAttribute.FAMILY, "SansSerif");
    aString.addAttribute(TextAttribute.FAMILY, "Serif", 8, 18);
    aString.addAttribute(TextAttribute.FOREGROUND, Color.orange, 8, 18);
    g2d.drawString(aString.getIterator(), 250, 170);

    g2d.drawString("Page: " + pageNum, 250, 190);
}

From source file:main.MapKit.java

@Override
public void paintWaypoint(Graphics2D g, JXMapViewer viewer, MyWaypoint w) {
    g = (Graphics2D) g.create();

    Point2D point = viewer.getTileFactory().geoToPixel(w.getPosition(), viewer.getZoom());
    int x = (int) point.getX();
    int y = (int) point.getY();

    if (w.amount == -1) { //means it's an original data point
        int fontSize = 28 - viewer.getZoom() * 2; //font size is larger when zoom in
        if (fontSize < 6)
            fontSize = 6;//from  w  w w. j av  a 2 s .  c  om
        g.setFont(new Font("Arial", Font.PLAIN, fontSize));
        g.setColor(w.color);
        g.drawString("x", x - fontSize / 2, y + fontSize / 2);
        g.dispose();
        return;
    }

    if (origImage == null) {
        return;
    }

    BufferedImage myImg = map.get(w.color);

    if (myImg == null) {
        myImg = convert(origImage, w.color);
        map.put(w.color, myImg);
    }

    g.drawImage(myImg, x - myImg.getWidth() / 2, y - myImg.getHeight(), null);

    String label = String.valueOf(w.amount);

    //      g.setFont(font);
    FontMetrics metrics = g.getFontMetrics();
    int tw = metrics.stringWidth(label);
    int th = 1 + metrics.getAscent();

    //      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawString(label, x - tw / 2, y + th);

    g.dispose();
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

/**
 * Draws a single character./*w  w  w  .j av  a2  s.  co m*/
 *
 * @param g2d
 *            {@link Graphics2D} context
 * @param ch
 *            character to draw
 * @param x
 *            left x position of the character
 * @param boxWidth
 *            width of the box
 */
private void drawCharacter(Graphics2D g2d, char ch, int x, int boxWidth) {
    double degree = (rnd.nextDouble() * rotationAmplitude * 2) - rotationAmplitude;
    double scale = 1 - (rnd.nextDouble() * scaleAmplitude / 100);

    Graphics2D cg2d = (Graphics2D) g2d.create();
    cg2d.setFont(font.deriveFont(fontSize));

    cg2d.translate(x + (boxWidth / 2), height / 2);
    cg2d.rotate(degree * PI / 90);
    cg2d.scale(scale, scale);

    FontMetrics fm = cg2d.getFontMetrics();
    int charWidth = fm.charWidth(ch);
    int charHeight = fm.getAscent() + fm.getDescent();

    cg2d.drawString(String.valueOf(ch), -(charWidth / 2), fm.getAscent() - (charHeight / 2));

    cg2d.dispose();
}

From source file:no.met.jtimeseries.chart.XYCloudSymbolRenderer.java

/**
 * Draws the visual representation of a single symbol.
 *///from   www  .  j  ava  2 s .c  o m
@Override
public void drawItem(Graphics2D g2d, XYItemRendererState state, Rectangle2D plotArea, PlotRenderingInfo info,
        XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item,
        CrosshairState crosshairState, int pass) {
    // Needs a new graphics object to use translate() and rotate()
    Graphics2D g2 = (Graphics2D) g2d.create();
    g2.setRenderingHints(renderHints);

    double middleY = plotArea.getCenterY();
    CloudDataset cloudData = (CloudDataset) dataset;
    Number x = cloudData.getX(series, item);
    double middleX = domainAxis.valueToJava2D(x.doubleValue(), plotArea, plot.getDomainAxisEdge());
    g2.translate((int) middleX, (int) middleY); // make x=0, y=0 the middle of the symbol
    g2.setStroke(new BasicStroke());
    double height = plotArea.getHeight() - 2;

    // we set the width to be 20 which is the same as the weather symbols 
    double width = calculateWidth(plotArea.getWidth());
    double startX = -(width / 2);
    double startY[] = { -(height / 2), -(height / 4), 0, (height / 4) };
    double values[] = { (cloudData.getHighClouds(series, item).doubleValue() / 100.0),
            (cloudData.getMediumClouds(series, item).doubleValue() / 100.0),
            (cloudData.getLowClouds(series, item).doubleValue() / 100.0),
            (cloudData.getFog(series, item).doubleValue() / 100.0) };

    for (int i = 0; i < values.length; i++) { // for each cloud type
        g2.setColor(new Color(96, 96, 96));
        g2.fill(new Rectangle2D.Double(startX, startY[i], (width * values[i]), (height / 4 - 1))); // plot could
        g2.setColor(new Color(97, 204, 247));
        g2.fill(new Rectangle2D.Double(startX + (width * values[i]), startY[i], (width * (1 - values[i])),
                (height / 4 - 1))); // plot sky
    }
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.JFreeChartReportDrawable.java

public void draw(final Graphics2D graphics2D, final Rectangle2D bounds) {
    this.bounds = (Rectangle2D) bounds.clone();
    if (chartRenderingInfo != null) {
        this.chartRenderingInfo.clear();
    }//from  w w w.  ja v  a  2  s .  c o  m
    final Graphics2D g2 = (Graphics2D) graphics2D.create();
    this.chart.draw(g2, bounds, chartRenderingInfo);
    g2.dispose();

    if (chartRenderingInfo == null || debugRendering == false) {
        return;
    }

    graphics2D.setColor(Color.RED);
    final Rectangle2D dataArea = getDataAreaOffset();
    final EntityCollection entityCollection = chartRenderingInfo.getEntityCollection();
    for (int i = 0; i < entityCollection.getEntityCount(); i++) {
        final ChartEntity chartEntity = entityCollection.getEntity(i);
        if (chartEntity instanceof XYItemEntity || chartEntity instanceof CategoryItemEntity
                || chartEntity instanceof PieSectionEntity) {
            final Area a = new Area(chartEntity.getArea());
            if (buggyDrawArea) {
                a.transform(AffineTransform.getTranslateInstance(dataArea.getX(), dataArea.getY()));
            }
            a.intersect(new Area(dataArea));
            graphics2D.draw(a);
        } else {
            graphics2D.draw(chartEntity.getArea());
        }
    }
}

From source file:org.tsho.dmc2.core.chart.CowebRenderer.java

private void animateCowebPlot(Graphics2D g2, Rectangle2D dataArea) {

    Graphics2D g2bisec = (Graphics2D) g2.create();
    g2bisec.setColor(Color.blue);

    Stroke stroke = new BasicStroke(3f);
    Stroke origStroke = g2.getStroke();
    Color color = Color.BLACK;
    g2blink = (Graphics2D) g2.create();
    g2blink.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    g2blink.setXORMode(color);//  ww w  .j a  v  a  2s .co  m
    g2blink.setStroke(stroke);

    if (plot.isAlpha()) {
        g2bisec.setComposite(AlphaComposite.SrcOver);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, plot.getForegroundAlpha()));
    }

    /* transients */
    stepper.setInitialValue(initialValue);
    stepper.initialize();

    state = STATE_TRANSIENTS;

    for (int index = 0; index < transients; index++) {

        stepper.step();

        if (stopped) {
            state = STATE_STOPPED;
            return;
        }
    }

    state = STATE_RUNNING;

    Range xDataRange = plot.getDataRange(domainAxis);
    int transX, transY, transX1, transY1;

    transX = (int) this.domainAxis.valueToJava2D(xDataRange.getLowerBound(), dataArea, RectangleEdge.BOTTOM);
    transY = (int) this.rangeAxis.valueToJava2D(xDataRange.getLowerBound(), dataArea, RectangleEdge.LEFT);
    transX1 = (int) this.domainAxis.valueToJava2D(xDataRange.getUpperBound(), dataArea, RectangleEdge.BOTTOM);
    transY1 = (int) this.rangeAxis.valueToJava2D(xDataRange.getUpperBound(), dataArea, RectangleEdge.LEFT);

    g2bisec.drawLine(transX, transY, transX1, transY1);

    //renderer.reset();

    recurseCoweb(g2, dataArea);
}

From source file:no.met.jtimeseries.chart.XYWindArrowRenderer.java

/**
 * Draws the visual representation of a single wind arrow.
 *///  w w  w .jav  a  2  s  . co  m
@Override
public void drawItem(Graphics2D g2d, XYItemRendererState state, Rectangle2D plotArea, PlotRenderingInfo info,
        XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item,
        CrosshairState crosshairState, int pass) {
    resizeArrowByPlotHeight((int) plotArea.getHeight());
    // Needs a new graphics object to use translate() and rotate()
    Graphics2D g2 = (Graphics2D) g2d.create();
    g2.setRenderingHints(renderHints);
    RectangleEdge domainAxisLocation = plot.getDomainAxisEdge();
    double middleY = plotArea.getCenterY();

    WindDataset windData = (WindDataset) dataset;

    Number x = windData.getX(series, item);
    Number windDir = windData.getWindDirection(series, item);
    Number wforce = windData.getWindForce(series, item);

    double middleX = domainAxis.valueToJava2D(x.doubleValue(), plotArea, domainAxisLocation);

    g2.translate((int) middleX, (int) middleY);
    g2.setColor(Color.BLACK);

    if (wforce.doubleValue() <= zeroWindLimit) {
        drawCircle(g2);
    } else {
        g2.rotate(Math.toRadians(windDir.doubleValue() - 180));
        drawArrow(g2, wforce.doubleValue());

        if (useArrowHead) {
            g2.fill(getPolygonHead(arrowHeadSize, arrowHeight));
        } else {
            g2.draw(getCircleHead(arrowHeadSize, arrowHeight));
        }
    }
}

From source file:LineGraphDrawable.java

/**
 * Draws the bar-graph into the given Graphics2D context in the given area.
 * This method will not draw a graph if the data given is null or empty.
 * /*from  ww  w . j  ava  2 s .co m*/
 * @param graphics
 *          the graphics context on which the bargraph should be rendered.
 * @param drawArea
 *          the area on which the bargraph should be drawn.
 */
public void draw(final Graphics2D graphics, final Rectangle2D drawArea) {
    if (graphics == null) {
        throw new NullPointerException();
    }
    if (drawArea == null) {
        throw new NullPointerException();
    }

    final int height = (int) drawArea.getHeight();
    if (height <= 0) {
        return;
    }

    final Graphics2D g2 = (Graphics2D) graphics.create();
    if (background != null) {
        g2.setPaint(background);
        g2.draw(drawArea);
    }

    if (data == null || data.length == 0) {
        g2.dispose();
        return;
    }

    g2.translate(drawArea.getX(), drawArea.getY());

    float d = getDivisor(data, height);
    final int spacing = getSpacing();
    final int w = (((int) drawArea.getWidth()) - (spacing * (data.length - 1))) / (data.length - 1);

    float min = Float.MAX_VALUE;
    for (int index = 0; index < data.length; index++) {
        Number i = data[index];
        if (i == null) {
            continue;
        }
        final float value = i.floatValue();
        if (value < min) {
            min = value;
        }
    }

    int x = 0;
    int y = -1;

    if (d == 0.0) {
        // special case -- a horizontal straight line
        d = 1.0f;
        y = -height / 2;
    }

    final Line2D.Double line = new Line2D.Double();
    for (int i = 0; i < data.length - 1; i++) {
        final int px1 = x;
        x += (w + spacing);
        final int px2 = x;

        g2.setPaint(color);

        final Number number = data[i];
        final Number nextNumber = data[i + 1];
        if (number == null && nextNumber == null) {
            final float delta = height - ((0 - min) / d);
            line.setLine(px1, y + delta, px2, y + delta);
        } else if (number == null) {
            line.setLine(px1, y + (height - ((0 - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        } else if (nextNumber == null) {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((0 - min) / d)));
        } else {
            line.setLine(px1, y + (height - ((number.floatValue() - min) / d)), px2,
                    y + (height - ((nextNumber.floatValue() - min) / d)));
        }
        g2.draw(line);

    }

    g2.dispose();

}

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

@Override
public void paint(Graphics2D g2, StateRenderer2D renderer) {
    Graphics2D g = (Graphics2D) g2.create();

    Point2D center = renderer.getScreenPosition(coords.squareCenter);
    double width = renderer.getZoom() * coords.cellWidth * coords.numCols;
    double height = renderer.getZoom() * coords.cellWidth * coords.numRows;
    g.setColor(new Color(0, 0, 255, 64));
    g.translate(center.getX(), center.getY());
    g.rotate(-renderer.getRotation());/*w w  w.j a v  a2 s . c  om*/
    g.fill(new Rectangle2D.Double(-width / 2, -height / 2, width, height));
    g.rotate(renderer.getRotation());
    g.translate(-center.getX(), -center.getY());

    if (!active) {
        g.dispose();
        return;
    }

    g.setColor(Color.orange);
    int pos = 50;
    for (String v : nameTable.values()) {
        g.drawString(v + ": " + depths.get(v) + "m", 15, pos);
        pos += 20;
    }

    for (String vehicle : nameTable.values()) {
        LocationType src = positions.get(vehicle);
        LocationType dst = destinations.get(vehicle);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());
        float dash[] = { 4.0f };
        g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash, 0.0f));
        g.draw(new Line2D.Double(renderer.getScreenPosition(src), renderer.getScreenPosition(dst)));

        Point2D dstPt = renderer.getScreenPosition(dst);

        if (!arrived.get(vehicle))
            g.setColor(Color.red.darker());
        else
            g.setColor(Color.green.darker());

        g.fill(new Ellipse2D.Double(dstPt.getX() - 4, dstPt.getY() - 4, 8, 8));
    }

    g.dispose();
}

From source file:com.versul.testes.JRViewerPanel.java

protected void paintPage(Graphics2D grx) {
    if (pageError) {
        paintPageError(grx);//from w  w w . j  av a 2 s  . c  om
        return;
    }

    try {
        if (exporter == null) {
            exporter = getGraphics2DExporter();
        } else {
            exporter.reset();
        }

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, viewerContext.getJasperPrint());
        exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, grx.create());
        exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(viewerContext.getPageIndex()));
        exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, new Float(realZoom));
        exporter.setParameter(JRExporterParameter.OFFSET_X, Integer.valueOf(1)); //lblPage border
        exporter.setParameter(JRExporterParameter.OFFSET_Y, Integer.valueOf(1));
        //            exporter.setParameter(JRExporterParameter.FILE_RESOLVER, viewerContext.getFileResolver());
        exporter.exportReport();
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Page paint error.", e);
        }

        pageError = true;

        paintPageError(grx);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(JRViewerPanel.this,
                        viewerContext.getBundleString("error.displaying"));
            }
        });
    }

}