Java Graphics Draw String drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)

Here you can find the source of drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text)

Description

draws the given unicode characters horizontally using the specified font.

License

Open Source License

Parameter

Parameter Description
graphics graphics context for drawing.
font font used for drawing the characters
dimension dimension in which to center the text.
text unicode characters to be drawn.

Declaration

public static void drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text) 

Method Source Code

//package com.java2s;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;

import java.awt.geom.Dimension2D;

import java.awt.geom.Rectangle2D;

public class Main {
    /**//from  w ww .  j  ava2s.  c o m
     * draws the given unicode characters horizontally using the specified font.
     * note: this method handles standard unicode characters as well as the supplementary unicode characters in the range 0x010000 - 0x10FFFF.
     * <br/><br/>
     * @param graphics    graphics context for drawing.
     * @param font        font used for drawing the characters
     * @param dimension   dimension in which to center the text.
     * @param text        unicode characters to be drawn.
     */
    public static void drawText(Graphics2D graphics, Font font, Dimension2D dimension, String text) {
        // determine the extent of the text box
        FontMetrics metrics = graphics.getFontMetrics(font);
        Rectangle2D bounds2d = metrics.getStringBounds(text, graphics);

        // determine the extent of the text
        double x = (dimension.getWidth() - bounds2d.getWidth()) / 2.0;
        double y = bounds2d.getHeight() / 2.0 - metrics.getLeading();

        // draw the text
        graphics.setFont(font);
        graphics.drawString(text, (float) x, (float) y);
    }
}

Related

  1. drawRightText(Graphics g, String str, int x, int y, int width, int height)
  2. drawRotatedShape(final Shape shape, final Graphics2D g2, final float x, final float y, final double angle)
  3. drawScaleLabel(Graphics g, String label, int x, int y, boolean yAxisP)
  4. drawSystemNameLabel(Graphics2D g, String sysName, Color color, double safetyOffset, boolean isLocationKnownUpToDate)
  5. drawText(Graphics graphics, int x, int y, String text)
  6. drawTextCenter(Graphics2D g2, String str, int x, int y)
  7. drawTextInBoundedArea(Graphics2D g2d, int x1, int y1, int x2, int y2, String text)
  8. drawTuplet(Graphics g, int x, int y, int x2, int y2, int bi, String s1, String s2)
  9. drawUnderlineCharAt(Graphics g, String text, int underlinedIndex, int x, int y)