Search code examples
androidcanvasdrawtext

How to rotate horizontally a text created by drawTextonPath in circle?


I have a function that draws a text on a canvas with drawTextOnPath. I calculated offset everything works fine, but I want to draw it in a particular way. Currently texts rotation offset is equal to circles offset. I want to rotate the text by 90/45 degrees. But I can not figure out how.

Please any ideas.

private void drawLegend(Canvas canvas) {
    canvas.save(Canvas.MATRIX_SAVE_FLAG);
    canvas.rotate(-228, centerX, centerY);

    Path circle = new Path();
    double halfCircumference = (radius * 2 * Math.PI) - ((radius * 2 * Math.PI) / 8) * 2;
    double increments = 5;

    for (int i = 0; i <= this.mMaxSpeed; i += increments) {
        circle.addCircle(centerX, centerY, radius, Path.Direction.CW);
        canvas.drawTextOnPath(String.format("%d", i),
                circle,
                (float) (i * halfCircumference / this.mMaxSpeed),
                -20f,
                scalePaint);
    }
    canvas.restore();
}

This is current mapping This is current mapping

Thi is how I wnat it to be displayed Thi is how I wnat it to be displayed


Solution

  • The solution was not to draw using drawTextOnPath but to draw on a canvas using drawText

            canvas.drawText(String.valueOf(0), (x - width / 2) + 35, (y + height / 2) - 25, scalePaint);
            canvas.drawText(String.valueOf(5), (x - width / 2) - 20, (y) + 8, scalePaint);
            canvas.drawText(String.valueOf(10), (x - width / 2) + 30, (y - height / 2) + 40, scalePaint);
            canvas.drawText(String.valueOf(15), (x), (y - height / 2) - 18, scalePaint);
            canvas.drawText(String.valueOf(20), (x + width / 2) - 30, (y  - height / 2) + 40, scalePaint);
            canvas.drawText(String.valueOf(25), (x + width / 2) + 25, (y) + 8, scalePaint);
            canvas.drawText(String.valueOf(30), (x + width / 2) - 35, (y + height / 2) - 25, scalePaint);
    

    UPDATE after 7 months

    The secret was to use sin and cos functions to calculate offset by x and by y.

    double theta = (7 * PI / 4) - (i * (2 * PI / 40));
    double xPos = radiusScale * 1.2 * Math.sin(theta) + centerX - widthText / 2;
    double yPos = radiusScale * 1.2 * Math.cos(theta) + centerY + heightText / 2;
    
    canvas.drawText(textNotch, (float)xPos, (float)yPos, scalePaint);