Tuesday, October 7, 2008

Centered text

When you want to draw some centered text, lets say, "Press any key" on your Splash, you can use

void paint (javax.microedition.lcdui.Graphics g) {
  g.drawString("Press any key", getWidth() / 2, getHeight(), Graphics.HCENTER | Graphics.BOTTOM);
}

But what if the default font is so small you can not read easily. Or worse, your text width is bigger than the screen width? To be sure you can use Font.stringWidth. Inside your paint method do something like:

int [] sizes = new int [] {Font.SIZE_LARGE, Font.SIZE_MEDIUM, Font.SIZE_SMALL};
int i = 0;
Font defaultFont = g.getFont();
// keep the same face and style, just want the biggest size that fits the screen
Font newFont = Font.getFont(defaultFont.getFace(), defaultFont.getStyle(), sizes[i]);
String m = "single line of text that fit the screen";

while (newFont.stringWidth(m) > getWidth()) {
i++;
newFont = Font.getFont(defaultFont.getFace(), defaultFont.getStyle(), sizes[i]);
}
g.setFont(newFont);

No comments: