I am developing a GPS waypoint application. I have started by drawing my compass but am finding it difficult to implement degree text around the circle. Can anyone help me with a solution? The compass image am working on] 1 here shows the circle of the compass I have drawn.
This image here shows what I want to achieve, that is implementing degree text round the compass [Image of what I want to achieve] 2
CodePudding user response:
Assuming you're doing this in a custom view, you need to use one of the drawText
methods on the Canvas
passed in to onDraw
.
You'll have to do a little trigonometry to get the x, y
position of the text - basically if there's a circle with radius r you're placing the text origins on (i.e. how far out from the centre they are), and you're placing one at angle θ:
x = r * cosθ
y = r * sinθ
The sin
and cos
functions take a value in radians, so you'll have to convert that if you're using degrees:
val radians = (degrees.toDouble() / 360.0) * (2.0 * Math.PI)
and 0 degrees is at 3 o'clock on the circle, not 12, so you'll have to subtract 90 degrees from your usual compass positions (e.g. 90 degrees on the compass is 0 degrees in the local coordinates). The negative values you get are fine, -90 is the same as 270. If you're trying to replicate the image you posted (where the numbers and everything else are rotating while the needle stays at the top) you'll have to apply an angle offset anyway!
These x and y values are distance from the centre of the circle, which probably needs to be the centre of your view (which you've probably already calculated to draw your circle). You'll also need to account for the extra space you need to draw those labels, scaling everything so it all fits in the View
CodePudding user response:
Thank you for your response. Please take a look at what I have done but it seems not to work. Pls help me review my code. Below is my code:
private val numbers = intArrayOf(30 , 60 , 90 , 120 , 150 , 180 , 210 , 240 , 270 , 300 , 330 , 0)
//I called the drawDegree function in my onDraw function
private fun drawDegree(canvas: Canvas) {
paint!!.textSize = fontSize.toFloat()
for (number in numbers) {
val tmp = number.toString()
paint!!.getTextBounds(tmp , 0 , tmp.length , rect)
val angle = Math.PI / 360
val x = (width / 2 Math.cos(angle) * radius * 0.7f - rect.width() / 2 200).toInt()
val y = (height / 2 Math.sin(angle) * radius * 0.7f rect.height() / 2 200).toInt()
canvas.drawText(tmp , x.toFloat() , y.toFloat() , paint!!)
}
}