Drawing the HUD
Now we get to use the drawText
method in the game. Add this highlighted code to the draw
method.
void draw() { gameView.setImageBitmap(blankBitmap); // Wipe the screen with a white color canvas.drawColor(Color.argb(255, 255, 255, 255)); // Change the paint color to black paint.setColor(Color.argb(255, 0, 0, 0)); // Draw the vertical lines of the grid canvas.drawLine(blockSize * 1, 0, blockSize * 1, numberVerticalPixels -1, paint); // Draw the horizontal lines of the grid canvas.drawLine(0, blockSize * 1, numberHorizontalPixels -1, blockSize * 1, paint); // Re-size the text appropriate for the // score and distance text paint.setTextSize(blockSize * 2); paint.setColor(Color.argb(255, 0, 0, 255)); canvas.drawText( "Shots Taken: " + shotsTaken + " Distance: " + distanceFromSub, blockSize, blockSize * 1.75f, paint); Log.d("Debugging", "In draw"); printDebuggingText(); }
First, we set the size of the text to blockSize * 2
. This is a simple way to make the size of the text relative to the number of pixels in the screen. Next, we use setColor
and pass (255, 0, 0, 255
) to the argb
method. This will make whatever we draw next, Blue.
The final new line of code in the draw
method is one long concatenation of text passed into the drawText
method. Look at the line carefully at just the arguments to foresee what text will be drawn.
"Shots Taken: " + shotsTaken + " Distance: " + distanceFromSub, blockSize, blockSize * 1.75f
We concatenate the words "Shots taken: " followed by the variable shotsTaken
then concatenate onto that the word " Distance: " followed by the variable distanceFromSub
.
The next two parameters determine the horizontal and vertical coordinates of the text. As with the grid lines, using blockSize
in the calculation will make the position relative to the many different sizes of screen that this game might be played on.
As with all our drawing methods, the final parameter is our object of type Paint
.
Let's update the debugging text to be drawn on the screen and then we can look at what we have achieved.