Friday, October 24, 2008

Vertically centered text

Images can be easily drawn at the center of the screen because Graphics.drawImage supports both anchors: HCENTER and VCENTER. To drawString we can use only HCENTER. If VCENTER is passed as argument an IllegalArgumentException is raised.
So how do we draw vertically centered text?
The maximum number of lines that fits the screen is obtained with a division:

int maxLinesPerScreen = getHeight() / Font.getDefaultFont().getHeight();

On a previous post we presented a way to split an String depending on the screen width. The result was a String array where each position represents a line that fits the screen. The programmer can choose to draw the text at any horizontal alignment.
But we can show them vertically centered too. We just need to calculate the pixel were the first
line is drawn 

int remainingLines = this.message.length - this.messageFirstLineShown;
int y = (remainingLines < maxLinesPerScreen) ?
  (getHeight() - (remainingLines * Font.getDefaultFont().getHeight())) / 2 : 
  (getHeight() - (maxLinesPerScreen * Font.getDefaultFont().getHeight())) / 2;
for (int i = this.messageFirstLineShown; i < this.message.length; i++) {
  g.drawString(this.message[i], getWidth() / 2, y, Graphics.HCENTER | Graphics.TOP);
  y += g.getFont().getHeight();
  // it was the last line that could be drawn
  if (y + Font.getDefaultFont().getHeight() > getHeight()) {
i = this.message.length; // stop the loop

No comments: