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:edu.kit.dama.ui.components.TextImage.java

/**
 * Get the bytes of the final image.//  www  .j  a  v  a 2 s.  c  om
 *
 * @return The byte array containing the bytes of the resulting image.
 *
 * @throws IOException if creating the image fails.
 */
public byte[] getBytes() throws IOException {
    Image transparentImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(
            new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB).getSource(), new RGBImageFilter() {
                @Override
                public final int filterRGB(int x, int y, int rgb) {
                    return (rgb << 8) & 0xFF000000;
                }
            }));

    //create the actual image and overlay it by the transparent background
    BufferedImage outputImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = outputImage.createGraphics();
    g2d.drawImage(transparentImage, 0, 0, null);
    //draw the remaining stuff
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.setColor(color);
    g2d.fillRoundRect(0, 0, size, size, 20, 20);
    g2d.setColor(new Color(Math.round((float) color.getRed() * .9f), Math.round((float) color.getGreen() * .9f),
            Math.round((float) color.getBlue() * .9f)));
    g2d.drawRoundRect(0, 0, size - 1, size - 1, 20, 20);

    Font font = new Font("Dialog", Font.BOLD, size - 4);
    g2d.setFont(font);
    g2d.setColor(Color.WHITE);

    String s = text.toUpperCase().substring(0, 1);
    FontMetrics fm = g2d.getFontMetrics();
    float x = ((float) size - (float) fm.stringWidth(s)) / 2f;
    float y = ((float) fm.getAscent()
            + (float) ((float) size - ((float) fm.getAscent() + (float) fm.getDescent())) / 2f) - 1f;
    g2d.drawString(s, x, y);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ImageIO.write(outputImage, "png", bout);
    g2d.dispose();
    return bout.toByteArray();
}

From source file:com.igormaznitsa.mindmap.swing.panel.MindMapPanel.java

private static void drawErrorText(final Graphics2D gfx, final Dimension fullSize, final String error) {
    final Font font = new Font(Font.DIALOG, Font.BOLD, 24);
    final FontMetrics metrics = gfx.getFontMetrics(font);
    final Rectangle2D textBounds = metrics.getStringBounds(error, gfx);
    gfx.setFont(font);//w  ww .j  a  v a 2  s  .c om
    gfx.setColor(Color.DARK_GRAY);
    gfx.fillRect(0, 0, fullSize.width, fullSize.height);
    final int x = (int) (fullSize.width - textBounds.getWidth()) / 2;
    final int y = (int) (fullSize.height - textBounds.getHeight()) / 2;
    gfx.setColor(Color.BLACK);
    gfx.drawString(error, x + 5, y + 5);
    gfx.setColor(Color.RED.brighter());
    gfx.drawString(error, x, y);
}

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

/**
 * Draws the wayPoint./*from w  ww . j a v  a 2s. c  om*/
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  an optional info object that will be populated with
 *              entity information.
 */
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    super.setGraphicsState(g2);

    if (!getPlotWrapper().okToDraw(this)) {
        return;
    }
    WayPoint leftWayPoint = getLeft();
    WayPoint rightWayPoint = getRight();
    g2.setStroke(new BasicStroke());
    int x1 = leftWayPoint.getXFromValue(dataArea, domainAxis);
    int x2 = rightWayPoint.getXFromValue(dataArea, domainAxis);
    int top = (int) (dataArea.getY());
    int bottom = (int) (dataArea.getY() + dataArea.getHeight());
    FontMetrics fm = g2.getFontMetrics();
    int width = fm.stringWidth(getName());
    int height = fm.getAscent() + fm.getDescent();
    if (getSelected()) {
        g2.setColor(Color.red);
    } else {
        g2.setColor(Color.black);
    }
    //      int y = bottom-3;
    y = top - 2;
    int textLeft = x1 + (x2 - x1) / 2 - width / 2;
    g2.drawString(getName(), textLeft, y);
    g2.setStroke(new BasicStroke(2.0f));
    g2.drawLine(x1, top + 1, x2, top + 1);
    g2.setStroke(new BasicStroke(1.0f));
    g2.setColor(Color.gray);
    g2.drawLine(x1, top, x1, bottom - WayPoint.ANNOTATION_WIDTH);
    g2.drawLine(x2, top, x2, bottom - WayPoint.ANNOTATION_WIDTH);
}

From source file:com.alibaba.simpleimage.render.CornerDrawTextItem.java

@Override
public void drawText(Graphics2D graphics, int width, int height) {
    if (StringUtils.isBlank(text)) {
        return;//from w w w  .  ja  v a 2  s .  co m
    }

    int x = 0, y = 0;
    // ?
    int textLength = (int) (width * textWidthPercent);
    // ??
    int fontsize = textLength / text.length();
    // ?.....?
    if (fontsize < minFontSize) {
        return;
    }

    float fsize = (float) fontsize;
    Font font = defaultFont.deriveFont(fsize);
    graphics.setFont(font);
    FontRenderContext context = graphics.getFontRenderContext();
    int sw = (int) font.getStringBounds(text, context).getWidth();

    // ??
    if (width > height) {
        y = height / 4;
    } else {
        y = width / 4;
    }

    int halflen = sw / 2;
    if (halflen <= (y - fontsize)) {
        x = y - halflen;
    } else {
        x = fontsize;
    }

    if (x <= 0 || y <= 0) {
        return;
    }

    if (fontShadowColor != null) {
        graphics.setColor(fontShadowColor);
        graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
    }
    graphics.setColor(fontColor);
    graphics.drawString(text, x, y);

    if (width > height) {
        y = height - (height / 4);
    } else {
        y = height - (width / 4);
    }

    halflen = sw / 2;
    if (halflen <= (height - y - fontsize)) {
        x = width - (height - y) - halflen;
    } else {
        x = width - sw - fontsize;
    }

    if (x <= 0 || y <= 0) {
        return;
    }

    if (fontShadowColor != null) {
        graphics.setColor(fontShadowColor);
        graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
    }
    graphics.setColor(fontColor);
    graphics.drawString(text, x, y);

}

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

private void drawOverlay() {
    this.frame += 1;
    overlay.beginRendering();/*  ww  w .  j a  va 2  s  . com*/
    Graphics2D g2d = overlay.createGraphics();
    try {
        if (getActiveCamera() != null) {
            FontRenderContext frc = g2d.getFontRenderContext();
            String cameraString = getActiveCamera().getLabel();
            GlyphVector gv = getOverlayFont().createGlyphVector(frc, cameraString);
            Rectangle bounds = gv.getPixelBounds(frc, 0, 0);
            int x = 5;
            int y = 5 + bounds.height;
            g2d.setFont(getOverlayFont());
            Color overlayColor = new Color(0.8f, 0.8f, 0.8f);
            Color transparentColor = new Color(0, 0, 0, 0);
            g2d.setBackground(transparentColor);
            g2d.setColor(overlayColor);
            g2d.clearRect(0, 0, getWidth(), height);
            if (isEnabled()) {
                g2d.drawString(cameraString, x, y);
            } else {
                g2d.drawString("Disabled", x, y);
            }
            if (System.currentTimeMillis() - lastFrameReset >= 500) {
                this.lastFrameReset = System.currentTimeMillis();
                this.fps = this.frame;
                this.frame = 0;
            }
            g2d.setColor(new Color(0.55f, 0.45f, 0.28f));
            g2d.drawString(String.valueOf(this.fps * 2) + "fps", x, y + bounds.height + 4);
            drawOverlayData(g2d);
            overlay.markDirty(0, 0, getWidth(), height);
            overlay.drawAll();

        }
    } catch (GkException e) {
        LOG.error(e);
    }
    g2d.dispose();
    overlay.endRendering();
}

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

private void renderDayMarkers(long pStart, long pEnd, Graphics2D pG2D) {
    Date d = new Date(pStart);
    d = DateUtils.setHours(d, 0);// www.  j av a  2 s  .c om
    d = DateUtils.setMinutes(d, 0);
    d = DateUtils.setSeconds(d, 0);
    d = DateUtils.setMilliseconds(d, 0);

    for (long mark = d.getTime(); mark <= pEnd; mark += DateUtils.MILLIS_PER_HOUR) {
        int markerPos = Math.round((mark - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(Color.YELLOW);
        pG2D.fillRect(markerPos, 20, 2, 10);
        pG2D.setColor(Color.WHITE);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.fillRect(markerPos - 5, 15, 12, 10);
        pG2D.setColor(Color.BLACK);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(mark));
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumIntegerDigits(2);
        f.setMaximumFractionDigits(2);
        pG2D.drawString(f.format(cal.get(Calendar.HOUR_OF_DAY)), markerPos - 5, 23);
    }

    long currentDay = d.getTime();
    while (currentDay < pEnd) {
        currentDay += DateUtils.MILLIS_PER_DAY;
        int markerPos = Math.round((currentDay - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(new Color(123, 123, 123));
        pG2D.fillRect(markerPos, 15, 3, 30);
        SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
        String dayLabel = f.format(currentDay);
        Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(dayLabel, pG2D);
        pG2D.setColor(Color.YELLOW);
        int labelWidth = (int) labelBounds.getWidth() + 5;
        pG2D.fillRect(markerPos - (int) Math.rint(labelWidth / 2), 15, labelWidth, 10);
        pG2D.setColor(Color.BLACK);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.drawString(dayLabel, markerPos - (int) Math.rint(labelWidth / 2) + 2, 23);
    }
}

From source file:net.pms.util.GenericIcons.java

/**
 * Add the format(container) name of the media to the generic icon image.
 *
 * @param image BufferdImage to be the label added
 * @param label the media container name to be added as a label
 * @param renderer the renderer configuration
 *
 * @return the generic icon with the container label added and scaled in accordance with renderer setting
 */// w  w w  . j a va2 s.co m
private DLNAThumbnail addFormatLabelToImage(String label, ImageFormat imageFormat, IconType iconType)
        throws IOException {

    BufferedImage image;
    switch (iconType) {
    case AUDIO:
        image = genericAudioIcon;
        break;
    case IMAGE:
        image = genericImageIcon;
        break;
    case VIDEO:
        image = genericVideoIcon;
        break;
    default:
        image = genericUnknownIcon;
    }

    if (image != null) {
        // Make a copy
        ColorModel colorModel = image.getColorModel();
        image = new BufferedImage(colorModel, image.copyData(null), colorModel.isAlphaPremultiplied(), null);
    }

    ByteArrayOutputStream out = null;

    if (label != null && image != null) {
        out = new ByteArrayOutputStream();
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        try {
            int size = 40;
            Font font = new Font(Font.SANS_SERIF, Font.BOLD, size);
            FontMetrics metrics = g.getFontMetrics(font);
            while (size > 7 && metrics.stringWidth(label) > 135) {
                size--;
                font = new Font(Font.SANS_SERIF, Font.BOLD, size);
                metrics = g.getFontMetrics(font);
            }
            // Text center point 127x, 49y - calculate centering coordinates
            int x = 127 - metrics.stringWidth(label) / 2;
            int y = 46 + metrics.getAscent() / 2;
            g.drawImage(image, 0, 0, null);
            g.setColor(Color.WHITE);
            g.setFont(font);
            g.drawString(label, x, y);

            ImageIO.setUseCache(false);
            ImageIOTools.imageIOWrite(image, imageFormat.toString(), out);
        } finally {
            g.dispose();
        }
    }
    return out != null ? DLNAThumbnail.toThumbnail(out.toByteArray(), 0, 0, ScaleType.MAX, imageFormat, false)
            : null;
}

From source file:org.csml.tommo.sugar.modules.QualityHeatMapsPerTileAndBase.java

void drawColumnHeader(Graphics2D g2, final ResultsTableModel model, int imgSize, int topBottomSeparator,
        int height, StringBuffer d) {
    // draw Top-Bottom header
    if (model.getTopBottomSeparatorColumn() > 0) {
        String s = "Top-Bottom";
        int stringWidth = g2.getFontMetrics().stringWidth(s);
        g2.drawString(s, 1 + imgSize * (model.getTopBottomSeparatorColumn() + 1)
                + (topBottomSeparator - 1 - stringWidth) / 2, 1 + height + 10 - 3);
    }//from   ww  w. j a  v  a2 s.co  m

    int separator = 0;
    for (int c = 0; c < model.getColumnCount(); c++) {
        d.append(model.getColumnName(c));
        d.append("\t");

        if (c == model.getTopBottomSeparatorColumn()) {
            d.append("Top-Bottom");
            d.append("\t");
        }
        Integer[] tiles = model.getTilesForColumn(c);
        for (int i = 0; i < tiles.length; i++) {
            String s = tiles[i].toString();
            int stringWidth = g2.getFontMetrics().stringWidth(s);
            g2.drawString(s, 1 + imgSize * c + (imgSize - 1 - stringWidth) / 2 + separator,
                    1 + height + 10 * (i + 1) - 3);
        }
        if (c == model.getTopBottomSeparatorColumn()) {
            separator = topBottomSeparator;
        }
    }
    d.append("\n");
}

From source file:org.esa.s2tbx.dataio.s2.l1b.L1bSceneDescription.java

public BufferedImage createTilePicture(int width) {

    Color[] colors = new Color[] { Color.GREEN, Color.RED, Color.BLUE, Color.YELLOW };

    double scale = width / sceneRectangle.getWidth();
    int height = (int) Math.round(sceneRectangle.getHeight() * scale);

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = image.createGraphics();
    graphics.scale(scale, scale);// w w  w .j a v a 2 s  . c o  m
    graphics.translate(-sceneRectangle.getX(), -sceneRectangle.getY());
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graphics.setPaint(Color.WHITE);
    graphics.fill(sceneRectangle);
    graphics.setStroke(new BasicStroke(100F));
    graphics.setFont(new Font("Arial", Font.PLAIN, 800));

    for (int i = 0; i < tileInfos.length; i++) {
        Rectangle rect = tileInfos[i].rectangle;
        graphics.setPaint(addAlpha(colors[i % colors.length].brighter(), 100));
        graphics.fill(rect);
    }
    for (int i = 0; i < tileInfos.length; i++) {
        Rectangle rect = tileInfos[i].rectangle;
        graphics.setPaint(addAlpha(colors[i % colors.length].darker(), 100));
        graphics.draw(rect);
        graphics.setPaint(colors[i % colors.length].darker().darker());
        graphics.drawString("Tile " + (i + 1) + ": " + tileInfos[i].id, rect.x + 1200F, rect.y + 2200F);
    }
    return image;
}

From source file:ru.runa.wfe.graph.image.figure.AbstractFigure.java

private int drawText(Graphics2D graphics, String text, int hOffset) {
    Rectangle r = getTextBoundsRectangle();
    Rectangle2D textBounds = graphics.getFontMetrics().getStringBounds(text, graphics);
    if (textBounds.getWidth() > r.getWidth() - 4) {
        int y = coords[1] + hOffset;
        AttributedString attributedString = new AttributedString(text);
        attributedString.addAttribute(TextAttribute.FONT, graphics.getFont());
        AttributedCharacterIterator characterIterator = attributedString.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, graphics.getFontRenderContext());
        while (measurer.getPosition() < characterIterator.getEndIndex()) {
            TextLayout textLayout = measurer.nextLayout((float) r.getWidth() - 4);
            y += textLayout.getAscent();
            float x = (float) (r.getCenterX() + 2 - textLayout.getBounds().getCenterX());
            textLayout.draw(graphics, x, y);
            y += textLayout.getDescent() + textLayout.getLeading();
        }/*w  ww.  j  a v  a 2  s.c  om*/
        return y - coords[1];
    } else {
        graphics.drawString(text, (float) (r.getCenterX() + 2 - textBounds.getCenterX()),
                (float) (coords[1] + textBounds.getHeight() + hOffset));
        return (int) (textBounds.getHeight() + hOffset + 3);
    }
}