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.
Beside adding CustomView programmatically, we can do that by updating main.xml file. We can using CustomView as an normal control in Android.
Don’t forget to update setContentView() method in the MainActivity class:
The final result after running the application:
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:
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:
So… It’s done for basic 2D graphic in Android! :D