## Drawing the Numbers

The following code draws the puzzle numbers on top of the tiles. The tricky part here is getting each number positioned and sized so it goes in the exact center of its tile.

// Define color and style for numbers

Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);

foreground.setColor(getResources().getColor(

R.color.puzzle_foreground)); foreground.setStyle(Style.FILL); foreground.setTextSize(height * 0.75f); foreground.setTextScaleX(width / height); foreground.setTextAlign(Paint.Align.CENTER);

 Game 3 6 4 2 3 8 4 2 7 4 6 3 8 2 1 4 5 1 3 2 1 9 7 oo 3 4 5

Figure 4.4: Centering the numbers inside the tiles

// Draw the number in the center of the tile FontMetrics fm = foreground.getFontMetrics(); // Centering in X: use alignment (and X at midpoint) float x = width / 2;

// Centering in Y: measure ascent/descent first float y = height / 2 - (fm.ascent + fm.descent) / 2; for (int i =0; i <9; i++) { for (int j =0; j <9; j++) {

canvas.drawText(this.game.getTi1eString(i, j), i

We call the getTileString() method (defined in Section 4.4, The Rest of the Story, on page 93) to find out what numbers to display. To calculate the size of the numbers, we set the font height to three-fourths the height of the tile, and we set the aspect ratio to be the same as the tile's aspect ratio. We can't use absolute pixel or point sizes because we want the program to work at any resolution.

To determine the position of each number, we center it in both the x and y dimensions. The x direction is easy—just divide the tile width by 2. But for the y direction, we have to adjust the starting position downward a little so that the midpoint of the tile will be the midpoint of the number instead of its baseline. We use the graphics library's FontMetrics class to tell how much vertical space the letter will take in total, and then we divide that in half to get the adjustment. You can see the results in Figure 4.4, on the preceding page.

That takes care of displaying the puzzle's starting numbers (the givens). The next step is to allow the player to enter their guesses for all the blank spaces.

0 0