Drawing some grid lines
Let's draw the first horizontal and vertical lines using the canvas.drawLine
method. However, soon we will see there is a gap in our knowledge. Add the highlighted lines of code.
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); Log.d("Debugging", "In draw"); printDebuggingText(); }
The first new line of code calls setColor
and changes the drawing color to black. The next line of code calls drawLine
. The parameters for drawline can be described as follows.
(starting horizontal coordinate, starting vertical coordinate, ending horizontal coordinate, ending vertical coordinate, our Paint object);
This causes a horizontal line to be drawn from blockSize, 0
(top left offset by one grid square) to blockSize, numberVerticalPixels -1
(bottom left). The next line of code draws a line from top left to top right again offset by one grid square.
If you need a refresher on how we arrived at the value stored in blockSize
refer to Chapter 3, Variables, Operators, and Expressions.
Run the game and look at the output. Here it is for your convenience.
We need to be able to run the same code over and over while each time adding one to the amount we multiply blockSize
by. Like this, blockSize * 1
, blockSize * 2
, blockSize * 3
and so on.
We could write a separate line of code for each line to draw but that would mean dozens of lines of code. We need to "loop" over the same code while manipulating a variable to represent the amount to multiply by. We will learn all about loops in the next chapter and then we will make this code work as it should.