Custom Rotary Knob Control for Android

Here's a new dynamic control for Android: a Rotary Knob. It can be used to adjust a value similar to a slider, but it is circular and has a certain advantage when it comes to aesthetics. Additionally it can be made to accept clicks, so besides working as a slider it can also function as a button. Either a momentary push button or a switch that can be toggled on or off.

And having said that, I'm sure you all know the Audio equipment volume buttons, that control both the volume and the on/off status of the particular device. Aslo in the software world, there are many audio/music applications that come with knobs that you can turn to set the volume.

Android implementation

The plan is to create a custom control, have it extend RelativeLayout and inside show two ImageViews, one would be the stator, a fixed image while the other one, the rotor, should be able to rotate over a given angle, while keeping the pivot at the center of our custom control. The control would also have two states, so when pressing the knob we would toggle from one state to another. To mark the two different positions, I will actually use two rotor images, one with a led turned on (green) and another one with it turned off (red/brown).
To intercept the user screen touches, we set a Touch listener. To make things easier (but not required), I have used a GestureDetector, exposing several callbacks of which I used three:

  2. public boolean onDown(MotionEvent event) ...
  3. public boolean onSingleTapUp(MotionEvent e) ...
  4. public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) ...

The first two are used for the toggle. If we press down and then press up at a location not far from the press down, then this is a simple click on the button.

  2. public boolean onDown(MotionEvent event) {
  3. float x = event.getX() / ((float) getWidth());
  4. float y = event.getY() / ((float) getHeight());
  5. mAngleDown = cartesianToPolar(1 - x, 1 - y);// 1- to correct our custom axis direction
  6. return true;
  7. }
  9. public boolean onSingleTapUp(MotionEvent e) {
  10. float x = e.getX() / ((float) getWidth());
  11. float y = e.getY() / ((float) getHeight());
  12. mAngleUp = cartesianToPolar(1 - x, 1 - y);// 1- to correct our custom axis direction
  14. // if we click up the same place where we clicked down, it's just a button press
  15. if (! Float.isNaN(mAngleDown) && ! Float.isNaN(mAngleUp) && Math.abs(mAngleUp-mAngleDown) < 10) {
  16. SetState(!mState);
  17. if (m_listener != null) m_listener.onStateChange(mState);
  18. }
  19. return true;
  20. }

If instead, we slide over our control, than we catch the movement in onScroll and we use it to rotate our rotor.

  2. public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
  3. float x = e2.getX() / ((float) getWidth());
  4. float y = e2.getY() / ((float) getHeight());
  5. float rotDegrees = cartesianToPolar(1 - x, 1 - y);// 1- to correct our custom axis direction
  7. if (! Float.isNaN(rotDegrees)) {
  8. // instead of getting 0-> 180, -180 0 , we go for 0 -> 360
  9. float posDegrees = rotDegrees;
  10. if (rotDegrees < 0) posDegrees = 360 + rotDegrees;
  12. // deny full rotation, start start and stop point, and get a linear scale
  13. if (posDegrees > 210 || posDegrees < 150) {
  14. // rotate our imageview
  15. setRotorPosAngle(posDegrees);
  16. // get a linear scale
  17. float scaleDegrees = rotDegrees + 150; // given the current parameters, we go from 0 to 300
  18. // get position percent
  19. int percent = (int) (scaleDegrees / 3);
  20. if (m_listener != null) m_listener.onRotate(percent);
  21. return true; //consumed
  22. } else
  23. return false;
  24. } else
  25. return false; // not consumed
  26. }

The angular interval is given to limit the rotation and give a start and stop point. For a volume knob, we will have a volume min and a volume max position corresponding to the limits of the permitted circular trajectory. But as pictures as better than words to illustrate a concept, here how this control looks like:

The math behind this control is simple. The user taps the control, so we get the touch coordinates as a (x,y) Cartesian pair. From it we compute the polar coordinates, that are used to know the rotation angle.

  2. private float cartesianToPolar(float x, float y) {
  3. return (float) -Math.toDegrees(Math.atan2(x - 0.5f, y - 0.5f));
  4. }

Knowing that the tangent of the angle is the length of the opposite side divided to the length of the adjacent side, we can compute the arctangent to get the Angle in radians. Then, with toDegrees, we get it in degrees, but working with radians directly is also ok.
As the direction of rotation that we consider is not the same with the trigonometric direction of rotation, a series of sign changing and complementary calculations are required. This - sign in the function above is also for this purpose, and so is the calling the function with 1 - value: cartesianToPolar(1 - x, 1 - y). But if you get a pen and a piece of paper like I did when making this, you'll easily understand the logic.

To rotate the imageview we use a matrix and postRotate:

  2. public void setRotorPosAngle(float deg) {
  3. if (deg >= 210 || deg <= 150) {
  4. if (deg > 180) deg = deg - 360;
  5. Matrix matrix=new Matrix();
  6. ivRotor.setScaleType(ScaleType.MATRIX);
  7. matrix.postRotate((float) deg, m_nWidth/2, m_nHeight/2);//getWidth()/2, getHeight()/2);
  8. ivRotor.setImageMatrix(matrix);
  9. }
  10. }
  11. public void setRotorPercentage(int percentage) {
  12. int posDegree = percentage * 3 - 150;
  13. if (posDegree < 0) posDegree = 360 + posDegree;
  14. setRotorPosAngle(posDegree);
  15. }

And finally , here is the result:
rotary_knob_android_custom_control 02

The source code

Code available under GPL v2, on Github or attached to this post, here.

Related Post

This article has 22 Comments

  1. This is very useful. Thank you.
    I see three issues:

    1 – I cannot get the 100% value (max is 99%)
    2 – The knob should continue from its current position when scrolled, and not start from where it is touched.
    3 – As a consequence of the previous point, when the max value is reached and I go on scrolling, it starts again from 0.

    But again, thank you!

  2. 1- To get the 100% value, try to change:
    int percent = (int) (scaleDegrees / 3);
    int percent = (int) (Math.round(scaleDegrees / 3));

  3. Like gb said, 1-how to continue from its current position when scrolled, but not start from where it is touched.
    2-how to improve when the max/min value is reached and I go on scrolling, it won’t starts again from 0 or 100.

  4. Nice job.
    But how can I use it in my project?
    I have a XML main_layout but I don’t know how should I add this knob to it.
    Please help me.

  5. Thank you dear Radu.
    I want to use the knob in a scrollview but the knob doesn’t work fine while rotating.
    How should I fix the issue?

  6. Hi, great work, thanks a lot!
    Do you have also a tutorial how to highlight the dots around the knob like in the first screenshots so that they match to the position of the knob and show the currently set value?
    Thanks and best regards!

  7. Hi,

    I read and tested your custom rotary knob i found here:

    However, i’m interested in expanding it’s features.

    As i see in the post, there’s an image with four different variations of this button.
    I’m interested in the third or fourth one, which have a circular bar which fills up. (one with stripes and one solid fill)
    Is it possible to send me that code? Or to get me on the way.

    The feature i want to add afterwards is that this circular loadbar drags along with your fingertip as you fill it up with x-y movement .
    A bit like the MIDI Designer application on Iphone.

    I’ve created some pictures for my analysis to illustrate this behaviour:

    I’t’s my first android program task.

    Thanks in advance for your feedback.

  8. How can I implement the RKB in my XML layout? Java layouting works, but unfortunately the XML results in an inflating error…

  9. I need to rotate the image from 0 to 100 and 100 to 0. If I am reaching at 100 the scroll to down it will move to 0 or other position. I require two if I am reaching at 100 position I don’t want to move down I need to work only 100 to 0 like fan knob. Is it possible?

  10. Change this row then the rotation works again:
    matrix.postRotate((float) deg, getWidth()/2, getHeight()/2); // 210/2,210/2);//

  11. I made a custom control from this that can be snapped into a fragment. I have 3 of them for bass, mid, and treble. My problem with my implementation at the moment is that the roforon image wobbles a bit as you turn it. I’m basically using the code you had in your sample with one in the center of your activity, Yours doesn’t wobble, mine does !! Great job with the graphics and trig explanation. I’m also concerned on how this is going to scale against lanscape/portrait, and differing device form factors.

Leave a Reply