Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to rotate Rect Object?

I have a rectangle: Rect r = new Rect();. I want to rotate the r object to 45 degrees. I checked for solutions and I found that it can be done with matrices:

Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r);

The problem is that whey I pass the r to m.mapRect(r); it complains that r should be from type RectF. I managed to do it like:

RectF r2 = new RectF(r);
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r2);

But the problem is that I need object from type Rect not RectF . Because I am passing the r object to external class which is taking a Rect object.

Is there another way to rotate the rectangle r form type Rect except this method and without rotationg the whole canvas(canvas contains some other elements)?

Thank you in advance!

Best regards, Dimitar Georgiev

like image 639
chikito1990 Avatar asked Nov 07 '13 13:11

chikito1990


1 Answers

Rotating a rectangle this way will not get you anything usable for drawing. A Rect and a RectF do not store any information about rotation. When you use Matrix.mapRect(), the output RectF is just a new non-rotated rect whose edges touch the corner points of the rotated rectangle that you are wanting.

You need to rotate the whole canvas to draw the rectangle. Then immediately unrotate the canvas to continue drawing, so there is no issue with rotating the canvas that has other objects in it.

canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();
like image 177
Tenfour04 Avatar answered Sep 27 '22 22:09

Tenfour04