Reputation: 1321
I want to be able to draw text and rectangles to the canvas after I have rotated them along their center. So I am making a test case where I have a blue square that does not get rotated, and a red square that should be rotated. THey are the same size, and should share the same center "pivot point". I have the following code:
Paint p = new Paint();
p.setColor(Color.CYAN);
p.setAlpha(200);
canvas.drawRect(new Rect(100,100,300,300), p);
canvas.save();
canvas.rotate(45,250,250);// 250,250 is the center of the blue rectangle
p.setColor(Color.RED);
p.setAlpha(100);
canvas.drawRect(new Rect(100,100,300,300), p);
canvas.restore();
It gives me a result close to what I want, but I am missing some math, because it looks like the canvas also needs a translation applied. Here is the result:
What I am missing so that I can rotate the red rectangle along the center of the blue one, and they end up sharing the same center point like this:
Upvotes: 2
Views: 2092
Reputation: 7708
The center of the blue rectangle is wrong.
center(x,y) = (left + (width/2), top + (height/2))
Note: width = 200, height = 200
so, center(x,y) = (200,200)
Change to this, and it works:
canvas.rotate(45,200,200);// 200,200 is the center of the blue rectangle
Upvotes: 3