David's Code to Rotate Text
Click here to see it
run
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
public class CreateRotatedImageExample extends Applet {
public static Frame offFrame = null;
public void init() {
if (offFrame == null) {
offFrame = new Frame();
offFrame.setBackground(Color.white);
offFrame.addNotify();
}
}
public void paint(Graphics g) {
FontMetrics fm = g.getFontMetrics();
Image rotatedLabelImage = createRotatedImage("Rotated Label", fm,
getFont(), getBackground(), getForeground());
g.drawImage(rotatedLabelImage, 0, 0, this);
}
/**
* Create an image of the string rotated 90 degrees to the left.
*
* @param s String to use in image
* @param fm FontMetrics object for font to use
* @param font Font to print label in
* @param backgroundColor The background color of the Image
* @param foregroundColor The foreground color of the Image
* @return The rotated image.
*/
public Image createRotatedImage(String s, FontMetrics fm, Font font,
Color backgroundColor, Color foregroundColor) {
Graphics fg = offFrame.getGraphics();
if (fm == null) {
System.out.println("FontMetrics is null.");
return null;
}
int w = fm.stringWidth(s) + 2;
int h = fm.getMaxAscent() + fm.getMaxDescent() + 2;
Image img = createImage(w, h);
Graphics g = img.getGraphics();
g.setColor(backgroundColor);
g.fillRect(0, 0, w, h);
g.setColor(foregroundColor);
g.setFont(font);
g.drawString(s, 1, fm.getMaxAscent() + 1);
g.dispose();
fg.drawImage(img, 0, 0, this);
fg.dispose();
int[] pixels = new int[w*h];
PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException ie) {
}
int[] newPixels = new int[w*h];
for (int y=0; y < h; ++y) {
for (int x=0; x < w; ++x) {
newPixels[x*h + y] = pixels[y*w + (w-x-1)];
}
}
MemoryImageSource imageSource = new MemoryImageSource(h, w,
ColorModel.getRGBdefault(), newPixels, 0, h);
Image myImage = createImage(imageSource);
MediaTracker mt = new MediaTracker(this);
mt.addImage(myImage, 0);
try {
mt.waitForAll();
} catch (InterruptedException ie) {
}
return myImage;
}
}