chikito1990
chikito1990

Reputation: 239

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

Upvotes: 9

Views: 18679

Answers (2)

Zain Ali
Zain Ali

Reputation: 15963

Another way to do this if you are applying rotation on your matrix then you should not use mapRect. you should figure out the 4 initial points representing each rectangle edge and use mapPoints instead.

float[] rectangleCorners = {
                            r2.left, r2.top, //left, top
                            r2.right, r2.top, //right, top
                            r2.right, r2.bottom, //right, bottom
                            r2.left, r2.bottom//left, bottom
                    };
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapPoints(r2);

Upvotes: 2

Tenfour04
Tenfour04

Reputation: 93609

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();

Upvotes: 12

Related Questions