Here you can find the source of drawCenteredText(Graphics2D g, String text, int x, int y, float align_x, float align_y, float font_size)
Parameter | Description |
---|---|
g | The Graphics context to use |
text | The text to draw |
x | The left side of the "bounding" box |
y | The top side of the "bounding" box |
align_x | The horizontal alignment of the text |
align_y | The vertical alignment of the text |
font_size | The font size to use |
public static void drawCenteredText(Graphics2D g, String text, int x, int y, float align_x, float align_y, float font_size)
//package com.java2s; //License from project: Open Source License import java.awt.*; import java.awt.geom.*; public class Main { /**//from w w w . ja va2 s . c o m * Draw text centered on a point * @param g The Graphics context to use * @param text The text to draw * @param x The left side of the "bounding" box * @param y The top side of the "bounding" box * @param align_x The horizontal alignment of the text * @param align_y The vertical alignment of the text * @param font_size The font size to use */ public static void drawCenteredText(Graphics2D g, String text, int x, int y, float align_x, float align_y, float font_size) { drawCenteredText(g, text, x, y, 0, 0, align_x, align_y, font_size); } /** * Draw text centered in a box * @param g The Graphics context to use * @param text The text to draw * @param x The left side of the "bounding" box * @param y The top side of the "bounding" box * @param width The width of the "bounding" box * @param height The height of the "bounding" box * @param align_x The horizontal alignment of the text * @param align_y The vertical alignment of the text * @param font_size The font size to use */ public static void drawCenteredText(Graphics2D g, String text, int x, int y, int width, int height, float align_x, float align_y, float font_size) { Font oldFont = null; if (font_size > 0) { oldFont = g.getFont(); g.setFont(g.getFont().deriveFont(font_size)); } Rectangle2D rect = g.getFontMetrics().getStringBounds(text, g); int x2 = (int) Math.round(x + align_x * (width - rect.getWidth()) - rect.getX()); int y2 = (int) Math.round(y + align_y * (height - rect.getHeight()) - rect.getY()); g.drawString(text, x2, y2); if (oldFont != null) g.setFont(oldFont); } }