Here you can find the source of drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize)
Parameter | Description |
---|---|
g2d | the graphics to draw to |
dim | the dimension to stay into |
drawString | the string to draw |
fontSize | chosen FontSize to draw with |
public static void drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize)
//package com.java2s; /*// ww w . j a v a 2s. c om * Copyright (C) 2010-2011 by Claas Anders "CaScAdE" Rathje * admiralcascade@gmail.com * Licensed under: Creative Commons / Non Commercial / Share Alike * http://creativecommons.org/licenses/by-nc-sa/2.0/de/ * */ import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; public class Main { /** * Draw a given String to a graphic object centered * * @param g2d the graphics to draw to * @param dim the dimension to stay into * @param drawString the string to draw * @param fontSize chosen FontSize to draw with */ public static void drawStringCentered(final Graphics2D g2d, final Dimension dim, final String drawString, final int fontSize) { Rectangle2D bounds; Object KEY_ANTIALIASING_before = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING); Object KEY_TEXT_ANTIALIASING_before = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); float posx = 0, posy = 0; g2d.setFont(g2d.getFont().deriveFont(Font.PLAIN, fontSize)); FontRenderContext frc = g2d.getFontRenderContext(); TextLayout tl = new TextLayout(drawString, g2d.getFont(), frc); bounds = tl.getBounds(); posx = (float) (dim.getWidth() / 2 - bounds.getCenterX()); posy = (float) (dim.getHeight() / 2 - bounds.getCenterY()); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, KEY_ANTIALIASING_before); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, KEY_TEXT_ANTIALIASING_before); g2d.drawString(drawString, (int) posx, (int) posy); } }