Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate a rectangle drawn on canvas in Android?

I am drawing a text on android canvas using the following piece of code

        Rect rect = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        canvas.translate(xPosition + position.getX(), yPosition + position.getY());
        paint.setColor(Color.BLUE);
        paint.setStyle(Style.STROKE);
        canvas.drawRect(rect, paint);
        paint.setStyle(Style.FILL);
        paint.setColor(text_color);
        canvas.translate(-(xPosition + position.getX()), -(yPosition + position.getY()));
        canvas.rotate(getDegreesFromRadians(angle), xPosition + position.getX() + rect.exactCenterX(), yPosition + position.getY() + rect.exactCenterY());
        canvas.drawText(text, xPosition + position.getX(), yPosition + position.getY(), paint);

This code takes care of the rotation of the text and it works fine. I am drawing a blue rectangle around the text using the above code. Now my problem is that the rectangle is not rotating along with the text. It still remains the same. Is there any way to rotate the rectangle drawn in android canvas?

like image 603
Antrromet Avatar asked Dec 16 '22 18:12

Antrromet


2 Answers

please use

canvas.save();
canvas.rotate();
//stuff to draw that should be rotated
canvas.restore();

else you have to compensate for every rotation afterwards

like image 197
NikkyD Avatar answered Dec 28 '22 13:12

NikkyD


I found my own answer. I used the following code

Rect rect = new Rect();
        paint.setColor(text_color);
        paint.setStyle(Style.FILL);
        paint.getTextBounds(text, 0, text.length(), rect);
        canvas.translate(xPosition + position.getX(), yPosition + position.getY());
        canvas.translate(-(xPosition + position.getX()), -(yPosition + position.getY()));
        canvas.rotate(getDegreesFromRadians(angle), xPosition + position.getX() + rect.exactCenterX(), yPosition + position.getY() + rect.exactCenterY());
        canvas.drawText(text, xPosition + position.getX(), yPosition + position.getY(), paint);
        paint.getTextBounds(text, 0, text.length(), rect);
        canvas.translate(xPosition + position.getX(), yPosition + position.getY());
        paint.setColor(Color.BLUE);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(4);
        rect = new Rect(rect.left - 10, rect.top - 10, rect.right + 10, rect.bottom + 10);
        canvas.drawRect(rect, paint);

The thing is the whole canvas is being rotated for rotating the text. So i just need to draw the rectangle after the rotation of the canvas.

like image 37
Antrromet Avatar answered Dec 28 '22 13:12

Antrromet