A lot of work was done this week, and hence the second blog post. A new UI element was introduced and I wanted to have a separate post with its details. So a circular slider it is, kind of like a volume rocker. How did I make one? Well, here goes.
So I wished to have some kind of an orbit on which the disk that denotes the value of the slider moves around. Why would anyone have anything other than a circle (more like a ring). So I used a disk. The average of the outer and inner radius of the disk is like a virtual circle on which the value disk would move.
Now, once a user clicks the value disk, it’s highly improbable (and also nearly impossible) for the user to follow the exact circle while sliding the value disk. Therefore, the previous method of capturing mouse coordinates and setting the center of the value disk to the position of the mouse coordinates while constraining the movement on a line won’t work here. We need to constrain the movement on a circle.
It’s time for some math.
Mathematically speaking, we have a circle, centered at (x1, y1). We have a click position, say (x2, y2). Now, the new position of the center of the value slider should lie on the line joining this point to the center of the circle and the circle itself. This is a simple case of a line-circle intersection!
I wrote down the equation of the circle and the line, used my algebra skills to get the following formula for finding the x coordinate of the intersections (two, since it’s a circle and the line passes through the center; the one nearer to the mouse coordinate makes more sense):
x = x1 +/- r(x2-x1)/(sqrt((x2-x1)^2 + (y2-y1)^2))
Where r is the radius of the constraint circle.
I plugged these values of x into the line equation to get the corresponding y values. The disk position is now this.
For this, I used angles. Same line, same circle as above. This time, I used the angle made by the line with the line parallel to the X-Axis and passing through the center of the circle. The percentage completion is now this angle by 360.
Here’s how it looks like.
The Final Result
Working as expected, this is the crude form of the circular slider we’ll use finally. Some animation and colors would probably make it tend more towards a futuristic slider.