1
2
3
4
5 package baseCode.graphics.text;
6
7 import java.awt.Component;
8 import java.awt.Font;
9 import java.awt.FontMetrics;
10 import java.awt.Graphics;
11 import java.awt.Graphics2D;
12 import java.awt.font.FontRenderContext;
13 import java.awt.font.TextLayout;
14 import java.awt.geom.AffineTransform;
15
16 /***
17 * @author Will Braynen
18 * @version $Id: Util.java,v 1.9 2004/07/27 03:18:58 pavlidis Exp $
19 */
20 public class Util {
21
22 /***
23 * @param text the string whose pixel width is to be measured
24 * @param font the pixels width of a string varies from font to font
25 * @param c the parent component; usually <code>this</code>
26 * @return the pixel width of the string for the specified font.
27 */
28 public static int stringPixelWidth( String text, Font font, Component c ) {
29
30 FontMetrics fontMetrics = c.getFontMetrics( font );
31 return fontMetrics.charsWidth( text.toCharArray(), 0, text.length() );
32
33 }
34
35 /***
36 * @param strings an array of strings whose pixels widths to compare
37 * @param font the pixels width of a string varies from font to font
38 * @param c the parent component; usually <code>this</code>
39 * @return the largest pixel width of a string in the <code>strings</code> array.
40 */
41 public static int maxStringPixelWidth( String[] strings, Font font,
42 Component c ) {
43
44
45 int maxWidth = 0;
46 int width;
47 String s;
48 for ( int i = 0; i < strings.length; i++ ) {
49 s = strings[i];
50 width = stringPixelWidth( s, font, c );
51 if ( maxWidth < width ) {
52 maxWidth = width;
53 }
54 }
55
56 return maxWidth;
57 }
58
59 /***
60 * Draws a string vertically, turned 90 degrees counter-clockwise. Read carefully what the <i>x </i> and <i>y </i>
61 * coordinates means; chances are that if you draw to (x,y) = (0,0), you won't see anything.
62 *
63 * @param g the graphics context on which to draw
64 * @param text the string to draw
65 * @param font the font to use
66 * @param x the <i>x </i> coordinate where you want to place the baseline of the text.
67 * @param y the <i>y </i> coordinate where you want to place the first letter of the text.
68 */
69 public static void drawVerticalString( Graphics g, String text, Font font,
70 int x, int y ) {
71 Graphics2D g2 = ( Graphics2D ) g;
72 AffineTransform fontAT = new AffineTransform();
73
74 fontAT.setToRotation( Math.PI * 3.0f / 2.0f );
75
76 FontRenderContext frc = g2.getFontRenderContext();
77 Font theDerivedFont = font.deriveFont( fontAT );
78 TextLayout tstring = new TextLayout( text, theDerivedFont, frc );
79 tstring.draw( g2, x, y );
80
81 }
82 }