Example usage for java.awt Graphics2D draw

List of usage examples for java.awt Graphics2D draw

Introduction

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

Prototype

public abstract void draw(Shape s);

Source Link

Document

Strokes the outline of a Shape using the settings of the current Graphics2D context.

Usage

From source file:edu.jhuapl.graphs.jfreechart.utils.SparselyLabeledCategoryAxis.java

private void drawDomainGridline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value) {
    Line2D line = null;/* w  w w  . j a  v a 2s  .  co  m*/
    PlotOrientation orientation = plot.getOrientation();

    if (orientation == PlotOrientation.HORIZONTAL) {
        line = new Line2D.Double(dataArea.getMinX(), value, dataArea.getMaxX(), value);
    } else if (orientation == PlotOrientation.VERTICAL) {
        line = new Line2D.Double(value, dataArea.getMinY(), value, dataArea.getMaxY());
    }

    g2.setPaint(domainGridlinePaint);
    Stroke stroke = plot.getDomainGridlineStroke();

    if (stroke == null) {
        stroke = CategoryPlot.DEFAULT_GRIDLINE_STROKE;
    }

    g2.setStroke(stroke);
    g2.draw(line);
}

From source file:org.amanzi.awe.render.network.NetworkRenderer.java

/**
 * render sector element on map/*from  w ww.j a va2s  . c  o m*/
 * 
 * @param destination
 * @param point
 * @param element
 */
private void renderSector(final Graphics2D destination, final Point point, final double azimuth,
        final double beamwidth, final IDataElement sector) {
    int size = getSize();
    int x = getSectorXCoordinate(point, size);
    int y = getSectorYCoordinate(point, size);
    destination.setColor(networkRendererStyle.changeColor(getColor(sector), networkRendererStyle.getAlpha()));
    GeneralPath path = new GeneralPath();
    path.moveTo(x, y);
    Arc2D a = createSector(point, networkRendererStyle.getLargeElementSize(), getAngle(azimuth, beamwidth),
            beamwidth);
    path.append(a.getPathIterator(null), true);
    path.closePath();
    destination.draw(path);
    destination.fill(path);
    // create border
    destination.setColor(networkRendererStyle.getBorderColor());
    destination.draw(path);
}

From source file:org.apache.fop.render.pcl.PCLPainter.java

private void drawTextAsBitmap(final int x, final int y, final int letterSpacing, final int wordSpacing,
        final int[] dx, final String text, FontTriplet triplet) throws IFException {
    //Use Java2D to paint different fonts via bitmap
    final Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize());

    //for cursive fonts, so the text isn't clipped
    final FontMetricsMapper mapper = (FontMetricsMapper) parent.getFontInfo().getMetricsFor(font.getFontName());
    final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000;
    final int ascent = mapper.getAscender(font.getFontSize()) / 1000;
    final int descent = mapper.getDescender(font.getFontSize()) / 1000;
    int safetyMargin = (int) (SAFETY_MARGIN_FACTOR * font.getFontSize());
    final int baselineOffset = maxAscent + safetyMargin;

    final Rectangle boundingBox = getTextBoundingBox(x, y, letterSpacing, wordSpacing, dx, text, font, mapper);
    final Dimension dim = boundingBox.getSize();

    Graphics2DImagePainter painter = new Graphics2DImagePainter() {

        public void paint(Graphics2D g2d, Rectangle2D area) {
            if (DEBUG) {
                g2d.setBackground(Color.LIGHT_GRAY);
                g2d.clearRect(0, 0, (int) area.getWidth(), (int) area.getHeight());
            }//from w w  w  .ja v a 2 s.c o  m
            g2d.translate(-x, -y + baselineOffset);

            if (DEBUG) {
                Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent);
                g2d.draw(rect);
                rect = new Rectangle(x, y - ascent, 2000, ascent);
                g2d.draw(rect);
                rect = new Rectangle(x, y, 1000, -descent);
                g2d.draw(rect);
            }
            Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state);
            try {
                painter.drawText(x, y, letterSpacing, wordSpacing, dx, text);
            } catch (IFException e) {
                //This should never happen with the Java2DPainter
                throw new RuntimeException("Unexpected error while painting text", e);
            }
        }

        public Dimension getImageSize() {
            return dim.getSize();
        }

    };
    paintMarksAsBitmap(painter, boundingBox);
}

From source file:edu.jhuapl.graphs.jfreechart.CategoryGraphBarPainter.java

@Override
public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar,
        RectangleEdge base) {/*  w  w w.jav a 2 s .  co m*/
    Paint itemPaint = itemProperty.get(row, column, Paint.class, renderer.getItemPaint(row, column),
            GraphSource.ITEM_COLOR);
    GradientPaintTransformer t = renderer.getGradientPaintTransformer();

    if (t != null && itemPaint instanceof GradientPaint) {
        itemPaint = t.transform((GradientPaint) itemPaint, bar);
    }

    g2.setPaint(itemPaint);
    g2.fill(bar);

    // draw the outline
    if (renderer.isDrawBarOutline()) {
        Stroke stroke = renderer.getItemOutlineStroke(row, column);
        Paint paint = renderer.getItemOutlinePaint(row, column);

        if (stroke != null && paint != null) {
            g2.setStroke(stroke);
            g2.setPaint(paint);
            g2.draw(bar);
        }
    }
}

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

private void drawRangeGridLine(Graphics2D g2, Rectangle2D dataArea, double value) {

    Range range = rangeAxis.getRange();/*  www. j  ava2  s. c o m*/
    if (!range.contains(value)) {
        return;
    }

    Line2D line = null;
    double v = rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);
    line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);

    g2.setPaint(gridPaint);
    g2.setStroke(gridStroke);
    g2.draw(line);

}

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

private void drawDomainGridLine(Graphics2D g2, Rectangle2D dataArea, double value) {

    Range range = domainAxis.getRange();
    if (!range.contains(value)) {
        return;/*from  w ww.j  a  va2 s.  co  m*/
    }

    Line2D line = null;
    double v = domainAxis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM);
    line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());

    g2.setPaint(gridPaint);
    g2.setStroke(gridStroke);
    g2.draw(line);

}

From source file:org.viafirma.util.QRCodeUtil.java

/**
 * Genera codigo de firma para impresin formado por el texto, el cdigo qr
 * del texto y un cdigo de barras con el cdigo de firma.
 * /* w ww.j  a  v a  2s.  co  m*/
 * @param text
 * @param codFirma
 * @return
 * @throws ExcepcionErrorInterno
 */
public byte[] generate(String text, String url, String textoQR, String codFirma) throws ExcepcionErrorInterno {
    // Comprobamos el tamao del texto. No recomendamos textos de mas de 120
    // caracteres
    if (textoQR.length() > MAX_TEXT_SIZE) {
        log.warn("El tamao del texto '" + text + "' ha excedido el tamao mximo. " + text.length() + ">"
                + MAX_TEXT_SIZE);
        textoQR = textoQR.substring(textoQR.lastIndexOf(" "));
        log.warn("El texto sera recortado: '" + textoQR + "'");
    }

    // Generamos la sufperficie de dibujo
    BufferedImage imagenQR = new BufferedImage(ANCHO_ETIQUETA, ALTO_ETIQUETA, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = imagenQR.createGraphics();
    // El fondo es blanco
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, ANCHO_ETIQUETA, ALTO_ETIQUETA);
    g.setColor(Color.BLACK);
    g.setStroke(new BasicStroke(2f));
    // Pintamos la caja de borde
    g.draw(new java.awt.Rectangle(MARGEN_CAJA, MARGEN_CAJA, ANCHO_ETIQUETA - MARGEN_CAJA * 2,
            ALTO_ETIQUETA - MARGEN_CAJA * 2));
    g.draw(new java.awt.Rectangle(MARGEN_CAJA + 3, MARGEN_CAJA + 3, ANCHO_ETIQUETA - MARGEN_CAJA * 2 - 6,
            ALTO_ETIQUETA - MARGEN_CAJA * 2 - 6));

    // Generamos el cdigo QR
    Qrcode x = new Qrcode();
    x.setQrcodeErrorCorrect('L');
    x.setQrcodeEncodeMode('B'); // Modo Binario
    byte[] d = textoQR.getBytes();
    // Generamos el cdigo QR
    boolean[][] s = x.calQrcode(d);
    for (int i = 0; i < s.length; i++) {
        for (int j = 0; j < s.length; j++) {
            if (s[j][i]) {
                g.fillRect(j * SIZE_QR + MARGEN, i * SIZE_QR + MARGEN, SIZE_QR, SIZE_QR);
            }
        }
    }
    int marjenSeparador = MARGEN + SIZE_QR * s.length + MARGEN_CAJA;
    int marjenTexto = marjenSeparador + MARGEN_CAJA;
    // Linea de separacin entre el QR cdigo y el texto
    g.drawLine(marjenSeparador - 3, MARGEN_CAJA + 3, marjenSeparador - 3, ALTO_ETIQUETA - MARGEN_CAJA - 3);
    g.drawLine(marjenSeparador, MARGEN_CAJA + 3, marjenSeparador, ALTO_ETIQUETA - MARGEN_CAJA - 3);

    // Linea de separacin entre texto y cdigo de barras.
    int marjenCodigoBarras = MARGEN + MAX_ROWS * FONT_SIZE;
    // Pintamos una pequea linea de separacin
    g.drawLine(marjenSeparador, marjenCodigoBarras, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras);
    g.drawLine(marjenSeparador, marjenCodigoBarras - 3, ANCHO_ETIQUETA - MARGEN_CAJA - 3,
            marjenCodigoBarras - 3);

    // Escribimos el texto
    List<String> parrafos = split(text);

    g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE));

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (int i = 0; i < parrafos.size(); i++) {
        String linea = parrafos.get(i);
        // Pintamos la nueva linea de texto
        g.drawString(linea, marjenTexto, MARGEN + 3 + (FONT_SIZE * i + 1));
    }

    g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE - 4));
    // Pintamos el texto final de una sola lnea( Generalmente el MD5 )
    //if(url.length())
    if (!url.equals("")) {
        g.drawString("Custodia del documento: ", marjenTexto, marjenCodigoBarras - 10 * 2);
        g.drawString(url, marjenTexto, marjenCodigoBarras - 6);
    }
    marjenCodigoBarras += MARGEN_CAJA;
    // Generamos el cdigo de barras
    try {
        // int marjenCodigoBarras=MARGEN+MAX_ROWS*FONT_SIZE;
        BarcodeFactory.createCode39(codFirma, true).draw(g, marjenTexto, marjenCodigoBarras);
    } catch (Exception e1) { // TODO
        e1.printStackTrace();
    }
    // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    // RenderingHints.VALUE_ANTIALIAS_OFF);

    // Finalizamos la superficie de dibujo
    g.dispose();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // Generamos la imagen
    try {
        ImageIO.write(imagenQR, "png", out);
        // ImageIO.write(imagenQR, "png", new
        // FileOutputStream("/tmp/imagen.png"));
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

    return out.toByteArray();
}

From source file:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java

/**
 * Initialize the work package calendar panel inclusive the listeners.
 *///from  w w w .  j  ava2  s  .c  om
private void init() {
    List<Workpackage> userWp = new ArrayList<Workpackage>(WpManager.getUserWp(WPOverview.getUser()));

    Collections.sort(userWp, new APLevelComparator());

    dataset = createDataset(userWp);
    chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);

    final JPopupMenu popup = new JPopupMenu();
    JMenuItem miSave = new JMenuItem(LocalizedStrings.getButton().save(LocalizedStrings.getWbs().timeLine()));
    miSave.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent arg0) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new ExtensionAndFolderFilter("jpg", "jpeg")); //NON-NLS
            chooser.setSelectedFile(new File("chart-" //NON-NLS
                    + System.currentTimeMillis() + ".jpg"));
            int returnVal = chooser.showSaveDialog(reference);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    File outfile = chooser.getSelectedFile();
                    ChartUtilities.saveChartAsJPEG(outfile, chart, chartPanel.getWidth(),
                            chartPanel.getWidth());
                    Controller.showMessage(
                            LocalizedStrings.getMessages().timeLineSaved(outfile.getCanonicalPath()));
                } catch (IOException e) {
                    Controller.showError(LocalizedStrings.getErrorMessages().timeLineExportError());
                }
            }
        }

    });
    popup.add(miSave);

    chartPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    });
    chartPanel.setMinimumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawHeight(50 + 15 * userWp.size());
    chartPanel.setMaximumDrawWidth(9999);
    chartPanel.setPreferredSize(
            new Dimension((int) chartPanel.getPreferredSize().getWidth(), 50 + 15 * userWp.size()));

    chartPanel.setPopupMenu(null);

    this.setLayout(new BorderLayout());

    this.removeAll();

    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1;
    constraints.weighty = 1;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    panel.add(chartPanel, constraints);

    panel.setBackground(Color.white);
    this.add(panel, BorderLayout.CENTER);

    GanttRenderer.setDefaultShadowsVisible(false);
    GanttRenderer.setDefaultBarPainter(new BarPainter() {

        @Override
        public void paintBar(final Graphics2D g, final BarRenderer arg1, final int row, final int col,
                final RectangularShape rect, final RectangleEdge arg5) {

            String wpName = (String) dataset.getColumnKey(col);
            int i = 0;
            int spaceCount = 0;
            while (wpName.charAt(i++) == ' ' && spaceCount < 17) {
                spaceCount++;
            }

            g.setColor(new Color(spaceCount * 15, spaceCount * 15, spaceCount * 15));
            g.fill(rect);
            g.setColor(Color.black);
            g.setStroke(new BasicStroke());
            g.draw(rect);
        }

        @Override
        public void paintBarShadow(final Graphics2D arg0, final BarRenderer arg1, final int arg2,
                final int arg3, final RectangularShape arg4, final RectangleEdge arg5, final boolean arg6) {

        }

    });

    ((CategoryPlot) chart.getPlot()).setRenderer(new GanttRenderer() {
        private static final long serialVersionUID = -6078915091070733812L;

        public void drawItem(final Graphics2D g2, final CategoryItemRendererState state,
                final Rectangle2D dataArea, final CategoryPlot plot, final CategoryAxis domainAxis,
                final ValueAxis rangeAxis, final CategoryDataset dataset, final int row, final int column,
                final int pass) {
            super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass);
        }
    });

}

From source file:BookTest.java

public void drawPage(Graphics2D g2, PageFormat pf, int page) {
    if (message.equals(""))
        return;/*from   w  ww  .j  av  a2  s  .c  om*/
    page--; // account for cover page

    drawCropMarks(g2, pf);
    g2.clip(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf.getImageableHeight()));
    g2.translate(-page * pf.getImageableWidth(), 0);
    g2.scale(scale, scale);
    FontRenderContext context = g2.getFontRenderContext();
    Font f = new Font("Serif", Font.PLAIN, 72);
    TextLayout layout = new TextLayout(message, f, context);
    AffineTransform transform = AffineTransform.getTranslateInstance(0, layout.getAscent());
    Shape outline = layout.getOutline(transform);
    g2.draw(outline);
}

From source file:org.fao.geonet.services.region.GetMap.java

public Element exec(Element params, ServiceContext context) throws Exception {
    Util.toLowerCase(params);/* w  w w.j a v  a2  s  . c om*/
    String id = params.getChildText(Params.ID);
    String srs = Util.getParam(params, MAP_SRS_PARAM, "EPSG:4326");
    String widthString = Util.getParamText(params, WIDTH_PARAM);
    String heightString = Util.getParamText(params, HEIGHT_PARAM);
    String background = Util.getParamText(params, BACKGROUND_PARAM);
    String geomParam = Util.getParamText(params, GEOM_PARAM);
    String geomType = Util.getParam(params, GEOM_TYPE_PARAM, GeomFormat.WKT.toString());
    String geomSrs = Util.getParam(params, GEOM_SRS_PARAM, "EPSG:4326");

    if (id == null && geomParam == null) {
        throw new BadParameterEx(Params.ID, "Either " + GEOM_PARAM + " or " + Params.ID + " is required");
    }
    if (id != null && geomParam != null) {
        throw new BadParameterEx(Params.ID, "Only one of " + GEOM_PARAM + " or " + Params.ID + " is permitted");
    }

    // see calculateImageSize for more parameter checks

    Geometry geom = null;
    if (id != null) {
        Collection<RegionsDAO> daos = context.getApplicationContext().getBeansOfType(RegionsDAO.class).values();
        for (RegionsDAO regionsDAO : daos) {
            geom = regionsDAO.getGeom(context, id, false, srs);
            if (geom != null) {
                break;
            }
        }
        if (geom == null) {
            throw new RegionNotFoundEx(id);
        }
    } else {
        GeomFormat format = GeomFormat.find(geomType);
        geom = format.parse(geomParam);
        if (!geomSrs.equals(srs)) {
            CoordinateReferenceSystem mapCRS = Region.decodeCRS(srs);
            CoordinateReferenceSystem geomCRS = Region.decodeCRS(geomSrs);
            MathTransform transform = CRS.findMathTransform(geomCRS, mapCRS, true);
            geom = JTS.transform(geom, transform);
        }
    }
    BufferedImage image;
    Envelope bboxOfImage = new Envelope(geom.getEnvelopeInternal());
    double expandFactor = 0.2;
    bboxOfImage.expandBy(bboxOfImage.getWidth() * expandFactor, bboxOfImage.getHeight() * expandFactor);
    Dimension imageDimenions = calculateImageSize(bboxOfImage, widthString, heightString);

    Exception error = null;
    if (background != null) {

        if (this.namedBackgrounds.containsKey(background)) {
            background = this.namedBackgrounds.get(background);
        }

        String minx = Double.toString(bboxOfImage.getMinX());
        String maxx = Double.toString(bboxOfImage.getMaxX());
        String miny = Double.toString(bboxOfImage.getMinY());
        String maxy = Double.toString(bboxOfImage.getMaxY());
        background = background.replace("{minx}", minx).replace("{maxx}", maxx).replace("{miny}", miny)
                .replace("{maxy}", maxy).replace("{srs}", srs)
                .replace("{width}", Integer.toString(imageDimenions.width))
                .replace("{height}", Integer.toString(imageDimenions.height)).replace("{MINX}", minx)
                .replace("{MAXX}", maxx).replace("{MINY}", miny).replace("{MAXY}", maxy).replace("{SRS}", srs)
                .replace("{WIDTH}", Integer.toString(imageDimenions.width))
                .replace("{HEIGHT}", Integer.toString(imageDimenions.height));

        InputStream in = null;
        try {
            URL imageUrl = new URL(background);
            in = imageUrl.openStream();
            image = ImageIO.read(in);
        } catch (IOException e) {
            image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
            error = e;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }

        }
    } else {
        image = new BufferedImage(imageDimenions.width, imageDimenions.height, BufferedImage.TYPE_INT_ARGB);
    }

    Graphics2D graphics = image.createGraphics();
    try {
        if (error != null) {
            graphics.drawString(error.getMessage(), 0, imageDimenions.height / 2);
        }
        ShapeWriter shapeWriter = new ShapeWriter();
        AffineTransform worldToScreenTransform = worldToScreenTransform(bboxOfImage, imageDimenions);
        //            MathTransform mathTransform = new AffineTransform2D(worldToScreenTransform);
        //            Geometry screenGeom = JTS.transform(geom, mathTransform);
        Shape shape = worldToScreenTransform.createTransformedShape(shapeWriter.toShape(geom));
        graphics.setColor(Color.yellow);
        graphics.draw(shape);

        graphics.setColor(new Color(255, 255, 0, 100));
        graphics.fill(shape);

    } finally {
        graphics.dispose();
    }

    File tmpFile = File.createTempFile("GetMap", "." + format);
    ImageIO.write(image, format, tmpFile);
    return BinaryFile.encode(200, tmpFile.getAbsolutePath(), true);
}