Search code examples
androidandroid-custom-view

Custom View - digits and alphabets on the circumference of a circle


Can anyone explain to me what is the cause of this behavior?

enter image description here

enter image description here

The problem is that, from "off" to "2" always shows perfectly, above the radius I gave. Radius is +35 than the circle's radius.

Now when I write digits, as it goes down, it starts to mess up.

And in terms of alphabets, it touches the edge and overlaps it.

can anyone tell me the reason for this? because radius is always more than the current circle's radius so the alphabets should appear similarly like "off".

computation of xy points...

// Angles are in radians.
   val startAngle = Math.PI * (9 / 8.0)   
   val angle = startAngle + pos.ordinal * (Math.PI / 4)
   x = (radius * cos(angle)).toFloat() + width / 2
   y = (radius * sin(angle)).toFloat() + height / 2

I played around with the degrees and it seems like the closer to 0 degree starts to mess up, as the degrees increase, it keeps adding more space in radius.

enter image description here

Illustrated here... I would like to what what is causing this behavior, or just explain the reason/ math behind it. thanks


Solution

  • From the comments it looks like you are following this code lab code https://github.com/google-developer-training/android-advanced/tree/master/CustomFanController

    You just need to take into account text ascent and decent. So draw the numbers on the circumference of the circle

    val yPos = (pointPosition.y - (paint.descent() + paint.ascent()) / 2).toInt() 
    canvas.drawText(label, pointPosition.x, yPos.toFloat(), paint)
    

    The above is based on Android Center text on canvas

    This does draw the text at the correct place, but if the text is too large it does overlap

    enter image description here