Example usage for java.awt Graphics2D drawString

List of usage examples for java.awt Graphics2D drawString

Introduction

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

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

Usage

From source file:nl.b3p.viewer.image.ImageTool.java

public static BufferedImage drawGeometries(BufferedImage bi, CombineImageSettings settings, int srid, Bbox bbox,
        int width, int height) throws Exception {
    List wktGeoms = settings.getWktGeoms();
    if (wktGeoms == null || wktGeoms.size() <= 0) {
        return bi;
    }/*from   www . j a  v a 2 s . c  o m*/
    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    //        BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gbi = newBufIm.createGraphics();
    gbi.drawImage(bi, 0, 0, null);
    for (int i = 0; i < wktGeoms.size(); i++) {
        gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        CombineImageWkt ciw = (CombineImageWkt) wktGeoms.get(i);
        Color color = settings.getDefaultWktGeomColor();
        if (ciw.getColor() != null) {
            color = ciw.getColor();
        }
        gbi.setColor(color);
        String wktGeom = ciw.getWktGeom();
        Geometry geom = geometrieFromText(wktGeom, srid);
        Shape shape = createImage(geom, srid, bbox, width, height);
        Point centerPoint = null;
        if (geom instanceof Polygon) {
            gbi.fill(shape);
        } else if (geom instanceof com.vividsolutions.jts.geom.Point) {
            centerPoint = calculateCenter(shape, srid, bbox, width, height);
            gbi.fill(new Ellipse2D.Double(centerPoint.getX(), centerPoint.getY(), 8, 8));
        } else {
            float strokeWidth = ciw.getStrokeWidth() != null ? ciw.getStrokeWidth() : 3f;
            gbi.setStroke(new BasicStroke(strokeWidth));
            gbi.draw(shape);
        }
        if (ciw.getLabel() != null) {
            if (centerPoint == null) {
                centerPoint = calculateCenter(shape, srid, bbox, width, height);
            }
            gbi.setColor(Color.black);
            gbi.drawString(ciw.getLabel(), (float) centerPoint.getX(), (float) centerPoint.getY());
        }
    }
    gbi.dispose();
    return newBufIm;
}

From source file:com.quinsoft.zeidon.objectbrowser.EntitySquare.java

private void paintCenteredText(Graphics2D graphics2, int y, String text, Color color) {
    Color prevColor = graphics2.getColor();
    if (color != null)
        graphics2.setColor(color);// w w  w  .  ja  v a  2 s . co  m

    FontMetrics fm = graphics2.getFontMetrics();

    String lines[] = text.split("\n");

    // Adjust y if there is more than one line.
    y -= (lines.length - 1) * fm.getHeight() / 2;

    for (String line : lines) {
        int lth = fm.stringWidth(line);
        int mid = size.width / 2;
        graphics2.drawString(line, mid - lth / 2, y);
        y += fm.getHeight();
    }

    if (color != null)
        graphics2.setColor(prevColor);
}

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

private void renderPopup(HashMap<String, Object> pPopupInfo, Graphics2D pG2D) {
    Point location = (Point) pPopupInfo.get("popup.location");
    String label = (String) pPopupInfo.get("popup.label");
    if (location == null || label == null) {
        return;/*from  ww  w.j av a2s  .  c om*/
    }
    pG2D.setColor(new Color(255, 255, 204));
    Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(label, pG2D);
    pG2D.fillRect(location.x, location.y - (int) labelBounds.getHeight(), (int) labelBounds.getWidth() + 5,
            (int) labelBounds.getHeight() + 5);
    pG2D.setColor(Color.BLACK);
    pG2D.drawRect(location.x, location.y - (int) labelBounds.getHeight(), (int) labelBounds.getWidth() + 5,
            (int) labelBounds.getHeight() + 5);
    pG2D.drawString(label, location.x + 2, location.y);

}

From source file:com.celements.photo.image.GenerateThumbnail.java

private void drawWatermark(String watermark, Graphics2D g2d, int width, int height) {
    //TODO implement 'secure' watermark (i.e. check if this algorithm secure or can it be easily reversed?)
    g2d.setColor(new Color(255, 255, 150));
    AlphaComposite transprency = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.45f);
    g2d.setComposite(transprency);/*from  w w w.  j  a v  a2 s  . c  o m*/

    FontMetrics metrics = calcWatermarkFontSize(watermark, width, g2d);
    g2d.setFont(calcWatermarkFontSize(watermark, width, g2d).getFont());

    // rotate around image center
    double angle = (Math.sin(height / (double) width));
    g2d.rotate(-angle, width / 2.0, height / 2.0);

    g2d.drawString(watermark, (width - metrics.stringWidth(watermark)) / 2,
            ((height - metrics.getHeight()) / 2) + metrics.getAscent());

    // undo rotation for correct copyright positioning
    g2d.rotate(angle, width / 2.0, height / 2.0);
}

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

/**
 * Draw black border around selected sector
 * /*from w  w  w  . j  av  a2s  .  c  om*/
 * @param destination
 * @param point
 * @param model
 * @param sector
 */
private void renderSelectionBorder(Graphics2D destination, Point point, ISectorElement sector, int index,
        int count) {
    Pair<Double, Double> sectorParameters = getSectorParameters(sector, index, count);
    int size = getSize();
    double azimuth = sectorParameters.getLeft();
    double beamwidth = sectorParameters.getRight();

    GeneralPath path = new GeneralPath();
    path.moveTo(getSectorXCoordinate(point, size), getSectorYCoordinate(point, size));
    Arc2D a = createSector(point, networkRendererStyle.getLargeElementSize(), getAngle(azimuth, beamwidth),
            beamwidth);
    path.append(a.getPathIterator(null), true);
    path.closePath();
    destination
            .setColor(networkRendererStyle.changeColor(SELECTED_SECTOR_COLOR, networkRendererStyle.getAlpha()));
    destination.draw(path);
    destination.drawString(sector.getName(), (int) a.getEndPoint().getX() + 10, (int) a.getEndPoint().getY());
}

From source file:io.github.karols.hocr4j.PageRenderer.java

/**
 * Renders this page on the given image.
 * The image is modified, not copied.//  w  w  w  .j  av  a2  s. c  om
 *
 * @param page page to render
 */
public void renderOnTop(@Nonnull Page page, @Nonnull BufferedImage img) {
    Graphics2D g = (Graphics2D) img.getGraphics();
    g.setColor(Color.RED);
    for (Area a : page) {
        for (Paragraph p : a) {
            for (Line l : p) {
                for (Word w : l.words) {
                    if (w.isBold()) {
                        if (w.isItalic()) {
                            g.setFont(boldItalicFont);
                        } else {
                            g.setFont(boldFont);
                        }
                    } else if (w.isItalic()) {
                        g.setFont(italicFont);
                    } else {
                        g.setFont(plainFont);
                    }
                    Bounds b = w.getBounds().scale(scale);
                    g.drawString(w.getText(), b.getLeft(), b.getBottom());
                }
            }
        }
    }
    g.setStroke(new BasicStroke(strokeWidth));
    g.setColor(defaultRectangleColor);
    for (Bounds rect : rectanglesToDraw) {
        if (rect != null) {
            Bounds b = rect.scale(scale);
            g.drawRect(b.getLeft(), b.getTop(), b.getWidth(), b.getHeight());
        }
    }
    for (Pair<Color, Bounds> rect : coloredRectanglesToDraw) {
        if (rect != null) {
            g.setColor(rect.getLeft());
            Bounds b = rect.getRight().scale(scale);
            g.drawRect(b.getLeft(), b.getTop(), b.getWidth(), b.getHeight());
        }
    }
}

From source file:uk.co.real_logic.aeron.tools.perf_tools.AeronLatencyUnderLoadPublisher.java

private void generateScatterPlot() throws IOException {
    final BufferedImage image = new BufferedImage(1800, 1000, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = image.createGraphics();
    final FontMetrics fm = g2.getFontMetrics();
    final String filename = "throughputency.png";
    final File imageFile = new File(filename);

    final int height = 940;
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    for (final long timestamp : timestamps) {
        final double ts = timestamp / 1000.0;
        if (ts < min) {
            min = ts;/* w w w . ja  v  a  2 s .c  o  m*/
        }
        if (ts > max) {
            max = ts;
        }
    }
    final double stepY = height / max;

    g2.setColor(Color.white);
    g2.fillRect(0, 0, 1800, 1000);
    g2.setColor(Color.black);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString("Latency ScatterPlot (microseconds)",
            900 - fm.stringWidth("Latency ScatterPlot (microseconds)") / 2, 20);
    g2.drawString("" + max, 10, 20);
    g2.drawLine(100, 20, 100, 960);
    g2.drawLine(100, 960, 1790, 960);
    int start = 0;
    int end = 100;
    final double width = 1690.0 / 7.0;
    g2.setColor(Color.red);
    plotSubset(g2, start, end, "10 msgs/sec", 100, width, stepY, means[0]);

    start = 100;
    end = 1100;
    g2.setColor(Color.green);
    plotSubset(g2, start, end, "100 msgs/sec", 100 + width, width, stepY, means[1]);

    start = 1100;
    end = 11100;
    g2.setColor(Color.blue);
    plotSubset(g2, start, end, "1K msgs/sec", 100 + width * 2, width, stepY, means[2]);

    start = 11100;
    end = 111100;
    g2.setColor(Color.cyan);
    plotSubset(g2, start, end, "10K msgs/sec", 100 + width * 3, width, stepY, means[3]);

    start = 111100;
    end = 1111100;
    g2.setColor(Color.magenta);
    plotSubset(g2, start, end, "100K msgs/sec", 100 + width * 4, width, stepY, means[4]);

    start = 1111100;
    end = 11111100;
    g2.setColor(Color.yellow);
    plotSubset(g2, start, end, "1M msgs/sec", 100 + width * 5, width, stepY, means[5]);

    start = 11111100;
    end = 41111100;
    g2.setColor(Color.orange);
    plotSubset(g2, start, end, "3M msgs/sec", 100 + width * 6, width, stepY, means[6]);

    ImageIO.write(image, "png", imageFile);
}

From source file:ucar.unidata.idv.control.chart.XYChartManager.java

/**
 * Set the label to use when we have an empty chart
 *
 * @param label empty chart label/*from   ww w  .j a  va  2s .  c o m*/
 */
public void setEmptyChartLabel(String label) {
    boolean signalChange = !Misc.equals(emptyChartLabel, label);
    if (emptyChartAnnotation == null) {
        signalChange = true;
        emptyChartAnnotation = new XYAnnotation() {
            public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis,
                    ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) {
                if (!hasStuff()) {
                    g2.setColor(Color.black);
                    g2.drawString(emptyChartLabel, 100, 50);
                }
            }

            @Override
            public void addChangeListener(AnnotationChangeListener arg0) {
            }

            @Override
            public void removeChangeListener(AnnotationChangeListener arg0) {
            }
        };
        for (int plotIdx = 0; plotIdx < chartHolders.size(); plotIdx++) {
            ChartHolder chartHolder = (ChartHolder) chartHolders.get(plotIdx);
            ((XYPlot) chartHolder.getPlot()).addAnnotation(emptyChartAnnotation);
        }
    }
    emptyChartLabel = label;
    if (signalChange) {
        signalChartChanged();
    }
}

From source file:org.optaplanner.examples.rocktour.swingui.RockTourWorldPanel.java

public void resetPanel(RockTourSolution solution) {
    translator = new LatitudeLongitudeTranslator();
    RockBus bus = solution.getBus();//w w  w.j  ava  2 s. co m
    translator.addCoordinates(bus.getStartLocation().getLatitude(), bus.getStartLocation().getLongitude());
    translator.addCoordinates(bus.getEndLocation().getLatitude(), bus.getEndLocation().getLongitude());
    for (RockShow show : solution.getShowList()) {
        translator.addCoordinates(show.getLocation().getLatitude(), show.getLocation().getLongitude());
    }

    Dimension size = getSize();
    double width = size.getWidth();
    double height = size.getHeight();
    translator.prepareFor(width, height);

    Graphics2D g = createCanvas(width, height);
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    List<RockShow> showList = solution.getShowList();
    int maxAvailableDateSetSize = showList.stream().mapToInt(show -> show.getAvailableDateSet().size()).max()
            .orElse(-1);
    for (RockShow show : showList) {
        RockLocation location = show.getLocation();
        int x = translator.translateLongitudeToX(location.getLongitude());
        int y = translator.translateLatitudeToY(location.getLatitude());
        double percentage = (double) show.getAvailableDateSet().size() / maxAvailableDateSetSize;
        g.setColor(TangoColorFactory.buildPercentageColor(TangoColorFactory.PLUM_3, TangoColorFactory.PLUM_1,
                percentage));
        g.fillRect(x - 1, y - 1, 3, 3);
        if (location.getCityName() != null && showList.size() <= 500) {
            g.drawString(StringUtils.abbreviate(location.getCityName(), 20), x + 3, y - 3);
        }
        if (show.getDate() != null) {
            g.drawString(DAY_FORMATTER.format(show.getDate()), x + 3, y - 3 + LOCATION_NAME_TEXT_SIZE * 3 / 2);
        }
    }
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    RockLocation busStartLocation = bus.getStartLocation();
    int domicileX = translator.translateLongitudeToX(busStartLocation.getLongitude());
    int domicileY = translator.translateLatitudeToY(busStartLocation.getLatitude());
    g.fillRect(domicileX - 2, domicileY - 2, 5, 5);
    if (busStartLocation.getCityName() != null && showList.size() <= 500) {
        g.drawString(busStartLocation.getCityName(), domicileX + 3, domicileY - 3);
    }
    Set<RockShow> needsBackToDomicileLineSet = new HashSet<>(showList);
    for (RockShow trailingShow : showList) {
        if (trailingShow.getPreviousStandstill() instanceof RockShow) {
            needsBackToDomicileLineSet.remove(trailingShow.getPreviousStandstill());
        }
    }
    g.setColor(TangoColorFactory.CHOCOLATE_1);
    for (RockShow show : showList) {
        if (show.getPreviousStandstill() != null) {
            RockLocation previousLocation = show.getPreviousStandstill().getDepartureLocation();
            RockLocation location = show.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), true, false);
            // Back to bus line
            if (needsBackToDomicileLineSet.contains(show)) {
                translator.drawRoute(g, location.getLongitude(), location.getLatitude(),
                        busStartLocation.getLongitude(), busStartLocation.getLatitude(), true, true);
            }
        }
    }
    g.setFont(g.getFont().deriveFont((float) TEXT_SIZE));
    // Legend
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    g.fillRect(5, (int) height - 17 - TEXT_SIZE, 5, 5);
    g.drawString("Bus start", 15, (int) height - 10 - TEXT_SIZE);
    g.setColor(TangoColorFactory.PLUM_2);
    g.fillRect(6, (int) height - 11, 3, 3);
    g.drawString("Show (darker means less available)", 15, (int) height - 5);
    repaint();
}

From source file:org.goko.viewer.jogl.service.JoglViewerServiceImpl.java

/** (inheritDoc)
 * @see org.goko.viewer.jogl.service.JoglSceneManager#drawOverlayData(java.awt.Graphics2D)
 *//*from www.  jav a  2 s  .c o m*/
@Override
protected void drawOverlayData(Graphics2D g2d) throws GkException {
    if (getCanvas().isKeyboardJogEnabled()) {
        // Draw a big red warning saying jog is enabled
        FontRenderContext frc = g2d.getFontRenderContext();
        String warn = "Keyboard jog enabled";
        GlyphVector gv = jogWarnFont.createGlyphVector(frc, warn);
        Rectangle bounds = gv.getPixelBounds(frc, 0, 0);
        int x = (getWidth() - bounds.width) / 2;
        int y = 5 + bounds.height;
        Rectangle2D bg = new Rectangle2D.Double(x - 5, 2, bounds.width + 15, bounds.height + 10);
        g2d.setFont(jogWarnFont);
        g2d.setColor(Color.RED);//new Color(0.9f,0,0,0.5f));
        g2d.fill(bg);
        g2d.setColor(Color.WHITE);
        g2d.drawString(warn, x, y);
    }

}