Learn to draw an Analog Clock on Android with the Canvas 2D API

To learn to use the Canvas 2D API, a good exercise is to draw an Analog Clock on Android. In this tutorial, you are going to discover how to create this kind of Clock and you will see some basics like creating a custom view and draw on a Canvas.

Note that you can enjoy this tutorial in video on Youtube :

The first step of the tutorial is to create a custom ClockView which will be used to draw the Analog Clock on the screen. To start, you need to define an initClock() method where you get the height and the width of the custom view. The minimum between the height and the width will be used to determine the dimensions of the square nesting the Analog Clock.

For the Analog Clock, we will define the radius by dividing the min between the height and the width by two. We subtract a padding value used to add some padding for the Analog Clock.

To draw the Analog Clock, we need to override the onDraw() method of our ClockView. If the view is not initialized, we call the initClock(). Then, we call the methods defined to draw the circle of the clock, the center, the numerals and the hands.

To update the time displayed on the Clock, we need to invalidate the view. Thus, it is drawn each 500 milliseconds.