Android 2D Graphic in Android

2D Graphic in Android

I - Introduction 2D Graphic in Android

In Android, to draw anything you always need 4 basic components:

  • An object type Bitmap to hold all the pixels you need to draw
  • An object hold all the drawing stroke (Rect, Path, Bitmap,...)
  • An object type Paint to define the color, style for your result
  • An object type Canvas to operate drawing command

II - Demo using CustomView

The demo below will show you how to implement 2D graphic in Android.

Firstly, create new a CustomView class that extends from View class.

We re-implement the constructor and override onDraw() method of View class, this method will take responsibility to draw the UI for CustomView.

2D Graphic in Android

As you can see in the code above, in onDraw() method, we create an Paint object and define the color property by setColor() method. After that, we add a circle in to the Path object using addCircle() method and finally we use the Canvas object to draw it on the view.

In the MainActivity, we update the content of setContentView() method with the input paramether is an CustomView object.

2D Graphic in Android


Beside adding CustomView programmatically, we can do that by updating main.xml file. We can using CustomView as an normal control in Android.

2D Graphic in Android

Don’t forget to update setContentView() method in the MainActivity class:

2D Graphic in Android

The final result after running the application:

2D Graphic in Android

Finally, You get the expected CustomView!

Beside drawing some simple shapes like circle, rectangle, oval, line,… we can draw the custom images.

To do that, firstly, we need to create an Bitmap object to hold all the pixels:

2D Graphic in Android

The Bitmap object is a kind of memory manager or file type format to save digital images. It’s a 2 dimensions array which each its item will hold a RGB color value - equals to a pixel of the image.

We can use BitmapFactory.decodeResource() method to create a Bitmap object from a image file in drawable folder.

Below is the result after running the application:

2D Graphic in Android

So… It’s done for basic 2D graphic in Android! :D

III - Download Source Code

This post is licensed under CC BY 4.0 by the author.