Search code examples
androidandroid-canvasandroid-custom-viewtrigonometryandroid-graphics

how to make custom view dial drawing numbers with trigonometry


Im trying to create an custom view that displays a dial with the numbers 1-10 around it. Im using trigonometry to find the X and Y positions for the numbers of the dial. I have no problems to find the positions around the circle but im unable to align them further in towards center of the dial. Look at number 6 for example, i just want it to be placed slightly above the thick white tick mark.

I have tried versions of "shortening the radius".

val diameter = Math.min(width, height)
val radius = diameter / 2 
val distance = radius * 0.20f //20% of radius

And then deduct 'distance' from radius to find the X and Y positions there and then add the numbers on those positions with no luck.

Below is the code that calculates the X and Y positions and adds the numbers displayed in the dial screenshot.

for (i in 1..10) {
canvas?.drawText(i.toString(),cx.toFloat() + 
(Math.cos(Math.toRadians(degrees.getInt(feetNumber,0).toDouble())).toFloat()) *     
radius - (paint.measureText(i.toString()) / 2),
                cy.toFloat() + 
(Math.sin(Math.toRadians(degrees.getInt(feetNumber,0).toDouble())).toFloat()) * 
radius + (paint.measureText(i.toString()) / 2), paint)

feetNumber++;
}

I have added the degrees in a array resource file.

<resources>
<array
  name="degrees">
  <item>270</item>
  <item>306</item>
  <item>342</item>
  <item>18</item>
  <item>54</item>
  <item>90</item>
  <item>126</item>
  <item>162</item>
  <item>198</item>
  <item>234</item>
</array>
</resources>

I would be very grateful if any one can help me to understand how to draw the numbers a short space after the thick tick marks where you usually find the numbers in a dial.

enter image description here


Solution

  • I have found a solution to my problem. The problem was that i cant calulate the radius in the canvas?.drawText() so i needed to privide pre-calculated value.

    val radius = diameter / 2
    val mark = radius * 0.30f
    val shorterRadius = radius - mark
    

    and then use the shorterRadius inside canvas?.drawText() along with the rest of the calculations.

    Then my dial look like the attached picture.

    enter image description here