Android Graphics and Animation: Part I

June 27th, 2011 by Keith Peters

This is the start of a series of tutorials on graphics and animation on the Android platform. There is plenty of information out there on how to create general form-based, controls-and-layout type of Android apps, but very little on how to do more creative drawing and animation. So this series will cover the following topics:

1. Android graphics.
2. Android animation.
3. Android input: Accelerometer.
4. Android input: Touch.

Today we’ll get started with simple graphics. There are actually a few different ways to draw graphics on the screen in Android.

First, there is the Canvas class, which gives you a nice basic drawing API to create lines, circles, rectangles, fills, strokes, deal with bitmaps, etc.

Then there’s OpenGL. If you’re going to do 3D or just need more raw graphics and animation power, you’ll probably want to use OpenGL, or more likely use one of the various 3rd party libraries that make it a bit easier to use.

And then there is something called RenderScript, which was introduced in Android 3.0 (which, at the time of this writing is supported by only a few devices).

For this set of articles, we’ll be using the simplest and most widely available option, Canvas.

Setting up an Android coding environment

Of course, before we can even get started, you’ll need to have an Android coding environment set up and a connected Android device. You could use the Android simulator, and you should use it for testing different device resolutions and capabilities, but in general day-to-day dev, you’ll probably find it faster and easier to deploy and test on a device.

I’m not going to go into very deep detail about this, only because Google has covered it in far more depth than I ever could. So I’ll just point you to the right place.

http://developer.android.com/index.html

Here you’ll find links to the SDK, Developer’s Guide, References, Resources, Videos, and a blog. Within all that, you’ll find step by step instructions on how to set up your environment. But in a nutshell, you’ll need to:
1. Install Eclipse (or another editor of your choice, but this tutorial will assume you’re using Eclipse).
2. Download the Android SDK. This is just a folder of files and tools used in developing Android apps.
3. Install the ADT Plugin, Android Development Tools. This is an Eclipse plugin that will set up your Eclipse install to build Android apps.
4. Add Android platforms and components.

These steps are all covered in more detail here:

http://developer.android.com/sdk/installing.html

Connecting a device or creating a virtual device (emulator)

Next you’ll need to have someplace to run your code. Again, I recommend using a real device as much as you can. Setting up a device for development is covered here:

http://developer.android.com/guide/developing/device.html

If you don’t have a physical device, or are at a point where you need to test some different resolutions or features your device doesn’t have, this link will walk you through setting up a virtual device on the emulator:

http://developer.android.com/guide/developing/devices/index.html

Code!

OK, let’s make an app. Assuming you have everything installed and working, and are using Eclipse as your editor, fire it up and create a new workspace. Then create a new project by using the menu File -> New -> Android Project. This will bring up the “New Android Project” dialog.

Give your project a name, “Drawing” and choose a Build Target. We’ll stick with Android 2.2 since that’s a pretty common one.

Going further down, we need an application name, package name, and activity name. The application name is what will show up on the device. For now, think of the activity name as the name of the main class of the app. The package is the class package as in any Java project. Finally we need to specify the minimum SDK version. We’ll choose 8 here to coincide with the Android 2.2 SDK. The whole numbering system for SDKs and SDK versions is a bit confusing. I’ll leave it to you to figure it out more on your own. But the above settings will work for now.

Now we can click “Finish” and our project will be created. Your package explorer view should look like this:

There you can see your src folder with your package and main activity class. Opening that class you should see the following code:

Since this is the only activity in this application, this class will be instantiated when the app is run, and the onCreate method will be called. This is where you want to hook into to initialize pretty much everything.

Right now, onCreate calls super.onCreate and then setContentView, passing in something called R.layout.main. If you’re curious what this is, look in the folder res/layout and you’ll see main.xml, which will look like this:

If you’ve done any work with Flex, Silverlight, or any other XML-based layout systems (or even HTML) this will look pretty familiar. It creates a layout with a single child that is a TextView. The TextView’s text property is set to “@string/hello”. If you want to see what that is, look in res/values/strings.xml.

The Android compiler will compile all the stuff in the res folder into classes or embeddable assets as appropriate. So res/layout/main.xml becomes the R.layout.main, which is an instance of a class that extends View and can be set as the activity’s content view using setContentView.

Now, if you’ve set everything up correctly, you should be able to run or debug this project on your device and/or in the emulator and see something like the following:

If this is not working, stop here and get it debugged. This is the bare bones of project setup, and everything else depends on this.

Custom Views

OK, that’s all very interesting, but we’re not going to use much in the res folder or any of that xml-based layout stuff here. We’re going down to the metal and writing our own drawing code.

But since we aren’t relying on the compiler to create a view from xml for us, we’ll have to make our own view class. We can even use some of the ADT plugin’s shortcuts to let it do a bunch of the work for us. Change Drawing.java to look like this:

Here we’ve created a new class member, drawingView of type View, instantiated it as a new DrawingView, passing in this to the constructor, and set it as the content view.

Of course, Eclipse will complain because DrawingView does not exist yet. But if we click on that error it will offer to create the class for you. It will even know that it should extend View. So go ahead and let it create that class. It should look like this:

Now it’s going to complain again because it wants a constructor that takes an argument. Again, use the quick fix feature to let it create the constructor it wants. Now you’ll have this:

We’re at a stable point here, so go ahead and run that on your device/emulator and make sure it launches. You shouldn’t see anything but a black screen with the app name at the top, but it should compile and deploy.

OK, now we have a view we can draw in. The View class is designed so that all the drawing will be done in an onDraw method. This method will be automatically called whenever the view needs to be redrawn. To create this method, type “onDraw”, trigger auto-complete, and accept the first choice. You should wind up with an onDraw method like you see below (or you could go all old school and actually type it by hand).

You see this method has given us a Canvas to draw on. If you trigger autocomplete on canvas, you’ll see that it has all kinds of drawing methods. Let’s add a call to drawLine right after the super.onDraw call:

As you probably guessed, the first arguments for this are the x, y values of an initial and an ending 2d point. The last argument, paint, is a Paint object that tells the system what to make this line look like (color, width, etc.). Since we haven’t defined paint yet, it will give you an error. Trigger a quick fix to create a field named paint. Then in the constructor we’ll instantiate it and give it some properties. Here’s the result:

Don’t forget the imports for Color and Style. You can run or debug this now and you should have an utterly fascinating diagonal white line on your device’s screen. When you’ve calmed down and gotten yourself under control, we’ll move on.

Setting the Background Color

Perhaps you want to change the background color. You can do that will canvas.drawColor, passing in the color you want to use. Note that this will actually clear the screen, so you’ll want to do this before drawing anything important.

Specifying Colors

In addition to the constants on the color class, like Color.BLACK, Color.WHITE, Color.RED, etc. you can specify exact colors with Color.rgb(red, green, blue) where each parameter is an int from 0 to 255, or Color.argb(alpha, red, green, blue) if you need transparency.

So to set the background to a kind of light purple, do something like this:

Other Shapes

As mentioned, there are lots of other options on Canvas for drawing various things. A few examples:

Here cx and cy are the center point to draw a circle with the given radius.

Here rect is a Rect object or a RectF object (which would use floats rather than ints for its measurements).

Pretty obvious.

Then there are drawOval, drawArc, drawRoundRect, and many others.

Putting it all together

Just to implement a few things all at once, we’ll do something like this for a final demo:

Here we’ve set the style to FILL instead of STROKE, then use some fancy math and a couple of for loops to draw a grid of squares, each with a random color. Nothing amazing, but assuming you have some previous experience with any kind of drawing API from any other language, this should set you up to create all kinds of custom graphics in your Android app or game.

Summary

Here we’ve seen how to set up a new Android project and create a custom view that we can draw into. The view class is instantiated and added as the activity’s main content view, and the onDraw method is called when it’s ready to display.

Of course, since generally speaking this is only called the one time near the start of the app, it’s just a static drawing. In the next installment of this series, we’ll dive into animation and making things move in Android.

, , ,