Please share...

  • Video courses

    All game programming videos just $19 - For a very limited time these three videos and thousands more are up to 90% off!

    Just enter coupon code NEWU19 in cart/checkout

Unity Pro Development A to Z – Build 10 Android/iOS Games

The Complete Android & Java Developer Course – Build 21 Apps

The Complete Java Developer Course. Learn Step by Step

In this really simple mini-project we will really harness the power of classes and objects by using classes from the Android API which allow us to draw graphics on the screen. We will see how we can draw shapes, lines, pixels, text and even custom designed graphics like game characters. We will do all of this by making objects of other people’s classes. We are then a big step closer to building our first real game.

  • Learning java by building Android games

    Learning Java by Building Android Games

    Want to learn Java for Android? Even if you are completely new to either Java, Android, or game programming but are aiming to publish Android games, then this book is for you. This book also acts as a refresher for those who already have experience in Java on other platforms or other object-oriented languages.
    • Setup your own Android game programming environment using Android Studio
    • Control logic, branch your code, and add real decision-making depth to your games
    • Design and use 2d sprite animations, smooth pixel graphics, sound FX, simple collision detection and artificial intelligence (AI)
    • Build around a dozen sample test apps and 4 complete working games!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    small_book

    Android Game Programming by Example

    Learn to build exciting Android game projects. Build a simple flappy-bird like game to a multi-environment, tough, retro platformer then an OpenGL ES 2 Asteroids clone, running at hundreds of frames per second .
    • Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
    • Every single line of code is printed in the book! No need to refer to the code files while trying to follow along. All the code files are also supplied separately so you can refer to them in their completed form and copy/paste them into your project if you like.
    • Implement a multitude of other game features such as pickups, firing weapons, HUD’s, generating and playing sound FX, scenery, level transition, high scores, and more
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US Only)

Create a new Android Studio project, call it Graphics Demo with a blank Activity called GraphicsDemoActivity. Delete all the code in GraphicsDemoActivity.java and enter the code below. Notice it has a few differences to our previous mini-projects. Also note that your project will have errors until we enter the rest of the code. Also, I have listed all the import... code. Remember you can either type this in now or wait until we use the appropriate class and press the Alt|Enter keyboard combination to enter the import... line automatically.

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;

public class GraphicsDemoActivity extends Activity {

    ImageView ourView;

    // This is the entry point to our game
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Do all our drawing in a separate method
        draw();

        // Make ourView ImageView object the view for the Activity
        setContentView(ourView);

    }
}

Notice that immediately below the class declaration we declare an object of the type ImageView called ourView. It is this ImgaeView class, provided by Android that we will use to draw upon. So why did we declare it outside of any method? The reason we did this is so that any methods in the class can “see” and use the method. Up until now, we have declared all of our objects and other variables in a method. We will not only use ourView in the onCreate method but also our draw method. Declaring it here makes this possible. This is called a member variable.

The next new thing in our code is the call to the draw method. This is a method that we will create in a moment and will draw on ourView. Notice then that we use the setContentView method just like all the other mini-projects but this time we pass in ourView. This makes whatever we draw on ourView appear on the screen. So let’s get on and implement our draw method.

Before we get coding we want to add a cute character graphic to our project files so we can use it in our drawing code. Meet Bob.

bob

You can download Bob by right-clicking on the image and selecting Save image as… Just make sure the file is named bob.png. Add the bob bitmap to the drawable folder in your Android Studio folders by dragging it there just like you would move any other file between folders on you PC. The drawable folder is shown in the next image.

Add the bob graphic into the drawable folder in Android Studio, directly. Don't use your operating system as it would be easy to get it wrong.

Add the bob graphic into the drawable folder in Android Studio, directly. Don’t use your operating system as it would be easy to get it wrong.

Now let’s implement our draw method. I am going to show you all the code at once so you can examine it and run it right away. We will dissect how it works when we have seen it in action. Enter the code as shown below. Make sure you do so just before the final closing curly brace } of the GraphicsDemoActivity class.

// This is our draw() method
    public void draw(){

        // Declare an object of type Bitmap
        Bitmap blankBitmap;
        // Make it 600 x 600 pixels in size and an appropriate format
        blankBitmap = Bitmap.createBitmap(600,600,Bitmap.Config.ARGB_8888);
        // Declare an object of type canvas
        Canvas canvas;
        // Initialize it by making its surface our previously created blank bitmap
        canvas = new Canvas(blankBitmap);

        // Initialize our previously declared member object of type ImageView
        ourView = new ImageView(this);
        // Put our blank bitmap on ourView
        ourView.setImageBitmap(blankBitmap);

        // We now have a surface ready to draw on
        // But we need something to draw with

        // Declare an object of type Paint
        Paint paint;
        // Initialize it ready for painting our canvas
        paint = new Paint();

        // Make the canvas white
        canvas.drawColor(Color.argb(255, 255, 255, 255));

        // Make the brush blue
        paint.setColor(Color.argb(255,  26, 128, 182));
        // We can change this around as well

        // Declare an object of type Bitmap
        Bitmap bitmapBob;
        // Initialize it using the bob.png file
        bitmapBob = BitmapFactory.decodeResource(this.getResources(), R.drawable.bob);
        // Now draw bob to our canvas
        canvas.drawBitmap(bitmapBob, 500, 50, paint);

        // Draw a line
        canvas.drawLine(50,50,250,250,paint);

        // Draw some text
        canvas.drawText("Game Code School", 50, 50, paint);

        // Draw a pixel
        canvas.drawPoint(40,50,paint);

        // Draw a circle
        canvas.drawCircle(350,250,100,paint);

        // Change the brush color
        paint.setColor(Color.argb(255,  249, 129, 0));

        // Draw a rectangle
        canvas.drawRect(50,450,500,550,paint);

        // Back to onCreate method to set our canvas as the view

    }

Here is what the code does chunk by chunk.

First, we have our method signature and the opening curly brace {.

// This is our draw() method
public void draw(){

Next, we do a number of things to create a virtual canvas on which to draw. If you try to imagine the internal workings of a graphics card and its relationship to the CPU and the complexity of how our graphics are stored in memory and then represented on the device screen it might give you a headache- it’s not simple. But what these four lines (excluding comments) do is vastly simplify the whole thing.

We create an object of type Bitmap, which we can think of as a blank graphic to draw upon. First, we declare it and then we initialize it using the createBitmap method. The method parameters are 600, 600, Config.ARGB_888, which are the length, width, and format of the bitmap.

Then we declare an object of type Canvas and immediately initialize it- with our blank Bitmap object. Here is that code again we will see how we use this new object of type Canvas really soon.

// Declare an object of type Bitmap
Bitmap blankBitmap;
// Make it 600 x 600 pixels in size and an appropriate format
blankBitmap = Bitmap.createBitmap(600,600,Bitmap.Config.ARGB_8888);
// Declare an object of type canvas
Canvas canvas;
// Initialize it by making its surface our previously created blank bitmap
canvas = new Canvas(blankBitmap);

Below we initialize ourView which is an ImageView object. Then we set blankBitmap as its image. Now anything we do with canvas will appear on ourView which you might remember we set as the view for the entire program in the onCreate method.

// Initialize our previously declared member object of type ImageView
ourView = new ImageView(this);
// Put our blank bitmap on ourView
ourView.setImageBitmap(blankBitmap);

// We now have a surface ready to draw on
// But we need something to draw with

Now we declare and initialize an object of the type Paint which perhaps unsurprisingly will allow us to paint on our canvas object.

// Declare an object of type Paint
Paint paint;
// Initialize it ready for painting our canvas
paint = new Paint();

Below we draw the entire screen as white using the drawColor method and we set the color of the brush we will be using in a moment to Game Code School blue. The four numbers that we use represent the level of transparency, red, green and blue. If you have not come across the RGB color model before have a quick look at this Wikipedia article. It is simply a way of describing a color using amounts of transparency, red, green and blue with values between 0 and 255.

// Make the canvas white
canvas.drawColor(Color.argb(255, 255, 255, 255));

// Make the brush blue
paint.setColor(Color.argb(255,  26, 128, 182));
// We can change this around as well

Next, we declare another Bitmap object then use the decodeResource() method to decode our bob.png file into a format suitable for use in our bitmapBob. Then we get to see our canvas object in action. we call the drawBitmap method of the Canvas class. The parameters are the bitmap to draw ( bitmapBob), the x,y screen location ( 500, 50) and our Paint object ( paint).

// Declare an object of type Bitmap
Bitmap bitmapBob;
// Initialize it using the bob.png file
bitmapBob = BitmapFactory.decodeResource(this.getResources(), R.drawable.bob);
// Now draw bob to our canvas
canvas.drawBitmap(bitmapBob, 500, 50, paint);

Now we draw a line with drawLine the numbers represent the starting and ending x,y coordinates of the line. Next in the code below we use drawText to perhaps unsurprisingly draw a String at a specific x,y location. After that, we draw a single pixel with drawPoint. Again we pass in the x, y location where we want the point and our object, paint.

// Draw a line
canvas.drawLine(50,50,250,250,paint);

// Draw some text
canvas.drawText("Game Code School", 50, 50, paint);

// Draw a pixel
canvas.drawPoint(40,50,paint);

We see next that we can also draw shapes like circles and rectangles with the respective methods of the Canvas class. Notice in between we change the color that we draw the rectangle with the setColor method. The parameters of drawCircle are the x, y screen location followed by the radius. The parameters of drawRect are the left, top, right and bottom locations that represent the rectangle.

// Draw a circle
canvas.drawCircle(350,250,100,paint);

// Change the brush color
paint.setColor(Color.argb(255,  249, 129, 0));

// Draw a rectangle
canvas.drawRect(50,450,500,550,paint);

Finally, we end the draw method with a closing curly brace } and execution returns to the onCreate method where you might remember we call setContentView(ourView) which displays all our lovely doodling to the screen.

// Back to onCreate method to set our canvas as the view

}

Run the code on an Android device if you haven’t already.

Having achieved what we just have it should not be too hard to imagine replacing the coordinates we used to draw our graphics with variables. We could then manipulate those variables to make them move, perhaps in some kind of loop. Now we are able to draw pixels, shapes, text for  perhaps a game’s GUI and bitmaps that can be used like sprites, we are so close to our first real game project I can nearly smell it.

Before we do we just need a little bit more Java knowledge. The logical next step is Handling game data with Java arrays.

Please visit the Android category of our game coding bookstore for beginners