Here you can find the source of drawFitText(Graphics2D g2, int x, int y, int width, int height, String text)
Parameter | Description |
---|---|
height | - not used yet! |
public static void drawFitText(Graphics2D g2, int x, int y, int width, int height, String text)
//package com.java2s; //License from project: Apache License import java.awt.FontMetrics; import java.awt.Graphics2D; public class Main { /**/* w w w.j a va 2s . c o m*/ * Draws text centered at the given position. Automatically inserts * line breaks. * @param height - not used yet! */ public static void drawFitText(Graphics2D g2, int x, int y, int width, int height, String text) { // get metrics from the graphics FontMetrics metrics = g2.getFontMetrics(g2.getFont()); // get the height of a line of text in this font and render context int hgt = metrics.getHeight(); int yOffset = hgt; // Set minimum width if (width < 10) { width = 10; } String remainingText = text; while (remainingText.length() > 0) { String currText = remainingText; // get the advance of my text in this font and render context int adv = metrics.stringWidth(currText); if (adv > width) { while (adv > width) { if (currText.lastIndexOf(' ') == 0) { currText = currText.substring(0, currText.length() - 2); } else { if (currText.lastIndexOf(' ') == -1) { currText = ""; remainingText = ""; } else { currText = currText.substring(0, currText.lastIndexOf(' ')); } } adv = metrics.stringWidth(currText); } } remainingText = remainingText.substring(currText.length()).trim(); // Draw the text g2.drawString(currText, x - width / 2, y + yOffset); // Increase yOffset (for more lines) yOffset += hgt; } } }