Learning Java by Building Android  Games
上QQ阅读APP看书,第一时间看更新

Initializing a Canvas, Paint, ImageView, and Bitmap

Now we can initialize our drawing based objects all in onCreate. Add the highlighted code.

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   // Get the current device's screen resolution
   Display display = getWindowManager().getDefaultDisplay();
   Point size = new Point();
   display.getSize(size);

   // Initialize our size based variables
   // based on the screen resolution
   numberHorizontalPixels = size.x;
   numberVerticalPixels = size.y;
   blockSize = numberHorizontalPixels / gridWidth;
   gridHeight = numberVerticalPixels / blockSize;

   // Initialize all the objects ready for drawing
   blankBitmap = Bitmap.createBitmap(numberHorizontalPixels,
         numberVerticalPixels,
         Bitmap.Config.ARGB_8888);

   canvas = new Canvas(blankBitmap);
   gameView = new ImageView(this);
   paint = new Paint();

   // Tell Android to set our drawing 
   // as the view for this app
   setContentView(gameView);

   Log.d("Debugging", "In onCreate");
   newGame();
   draw();
}

Again, this code mirrors exactly what we did in the Canvas demo. With one small but crucial exception.

You might be wondering where the call to setImageBitmap is? As we will need to draw the image over and over as the image will be slightly different each time we have moved the call to setImageBitmap to the draw method where it can be called each time we redraw the screen.

Finally, we will get to see some results after this next code. Add the new highlighted code to the end of the draw method.

/*
   Here we will do all the drawing.
   The grid lines, the HUD,
   the touch indicator and the
   "BOOM" when the sub' is hit
 */
void draw() {
   gameView.setImageBitmap(blankBitmap);

   // Wipe the screen with a white color
   canvas.drawColor(Color.argb(255, 255, 255, 255));

   Log.d("Debugging", "In draw");
   printDebuggingText();
}

The previous code sets blankBitmap to gameView and clears the screen with the call to drawColor using the argb method to pass in the required values (255, 255, 255, 255) for a blank white screen.

Run the game and check that you have the same result as this next image.

Initializing a Canvas, Paint, ImageView, and Bitmap

It's still not "Call of Duty", but we can clearly see that we have drawn a white screen. And if you were to tap the screen it would redraw each time although obviously, this is unnoticeable because it doesn't change yet. Now we have reached this point we will see regular improvements in what we can draw. Each project from now on will contain similar aspects to the drawing code making visual progress much faster.