Here you can find the source of drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
Parameter | Description |
---|---|
graphics | graphics context for drawing. |
font | font used for drawing the text. |
dimension | dimension in which to center the text. |
text | standard unicode text (0x0000 - 0xFFFF)to be drawn. |
public static void drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text)
//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; import java.util.ArrayList; import java.util.List; public class Main { /**/*from w w w.j a va2 s . com*/ * draws the given text vertically using the specified font. * note: each characters in the text must be in the orignal unicode range of 0x0000 - 0xFFFF. * <br/><br/> * @param graphics graphics context for drawing. * @param font font used for drawing the text. * @param dimension dimension in which to center the text. * @param text standard unicode text (0x0000 - 0xFFFF)to be drawn. */ public static void drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, String text) { List<String> strings = new ArrayList<String>(); for (Character c : text.toCharArray()) { strings.add(c.toString()); } drawVerticalText(graphics, font, dimension, strings); } /** * Draws each strings using the specified font. * Each string in the list is centered horizontally, and spaced vertically * to fill in the space given by the dimension. * <br/><br/> * @param graphics * graphics context for drawing. * @param font * font used for drawing the strings * @param dimension * dimension in which to center the strings * @param strings * list of strings to draw in the dimension */ public static void drawVerticalText(Graphics2D graphics, Font font, Dimension2D dimension, List<String> strings) { // determine the extent of the text. FontMetrics metrics = graphics.getFontMetrics(font); double textHeight = metrics.getAscent(); double leading = metrics.getLeading(); double descent = metrics.getDescent(); // Vertical offset between each line of text. double vOffset = dimension.getHeight() / strings.size(); // loop through each character for (int i = 0; i < strings.size(); ++i) { // determine the extent of the text box. String text = strings.get(i); Rectangle2D bounds2d = metrics.getStringBounds(text, graphics); // Get the top and bottom y coordinates that the string is centered in. double startY = i * vOffset; double stopY = (i + 1) * vOffset; // get how much white space is left in the vertical area. double verticalSpace = (stopY - startY) - textHeight; // center the text in the area. double x = (dimension.getWidth() - bounds2d.getWidth()) / 2.0; double y = stopY - verticalSpace / 2.0; // Draw the text. graphics.setFont(font); graphics.drawString(text, (float) x, (float) (y - leading - descent / 2.0)); } } }