How do I build a graphical needle gauge UI widget in Android?

marlar picture marlar · May 24, 2011 · Viewed 7.5k times · Source

I need a graphical needle gauge (like a speedometer etc) for my app but such a UI widget is not part of the SDK so I probably have to create it myself.

My idea is to have the background with the tickmarks and coloured fields (green, yellow, red) as one bitmap and the needle as another bitmap drawn on top of the background, but rotated in the appropriate angle.

In my book, Professional Android 2 Application Development, there is a somewhat similar example with a compass rose, although that one is drawn using line graphics, not pre-fabricated images like I will have to use to get the desired look.

However, in the compass example the whole canvas is rotated before drawing the tick marks. I cannot use this approach as it will also rotate the gauge background. So I need to somehow rotate the needle image (which should be transparent) before superimposing it. But I don't know how to do accomplish this.

Can anyone lead me in the right direction on how to proceed with the needle gauge? Also, if there is a better way to build the meter than sketched above, please let me know.

Answer

Olegas picture Olegas · May 24, 2011

You can divide your guage into different layers. One for background, one for tick marks. Layer for tick marks can be rotated to draw marks and when turned back and combined with 'background' layer.

You can see the following example with layer technique described above: http://mindtherobot.com/blog/534/android-ui-making-an-analog-rotary-knob/

P.S. This is not my blog, i've just found this technique there.