How to rotate a rectangle drawn on a canvas in Android?

I draw text on android canvas using the following code snippet

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 great. I draw a blue rectangle around the text using the code above. Now my problem is that the rectangle does not rotate with the text. He still remains the same. Is there a way to rotate the rectangle drawn on android canvas?

+4
source share
2 answers

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 fact is that the entire canvas rotates to rotate the text. So I just need to draw a rectangle after turning the canvas.

+2
source

use

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

otherwise you will have to compensate every turn afterwards

+10
source

Source: https://habr.com/ru/post/1441790/


All Articles