旋转的rect更改位置

时间:2014-10-15 01:42:00

标签: java android canvas rotation

我正在尝试旋转一个矩形,我必须旋转画布才能这样做,但是矩形改变了它的位置,例如,如果在旋转之后矩形位于屏幕中间,它将转到侧面而我无法弄清楚如何让它回到中间。

以下是我使用的代码:

    canvas.save();
    canvas.rotate(45);
    canvas.drawRect(width/2,height/2, width/2+200, height/2+200, paint);
    canvas.restore();

有没有办法在不旋转画布的情况下旋转矩形,使其位置保持不变?

2 个答案:

答案 0 :(得分:1)

您的矩形中心与画布的轴心点不同。您可以尝试使用the other rotate method指定轴心点的x / y坐标。如:

int offset = 200;
int left = width/2;
int top = height/2;
int right = left + offset;
int bottom = top + offset;

canvas.save();
canvas.rotate(45, left + offset/2, top + offset/2);
canvas.drawRect(left, top, right, bottom, paint);
canvas.restore();

编辑:

刚刚测试了上面的代码,并验证了它的工作原理(给出了我刚才添加的一些调整)。

答案 1 :(得分:0)

'canvas.rotate'围绕画布原点旋转画布。原点是初始状态下画布的左上角。 如果要围绕矩形的中心旋转矩形,请在使用'canvas.rotate'之前将画布的原点移动到rectancle的中心。

请尝试以下代码:

canvas.save();
canvas.drawRect(width/2,height/2, width/2+200, height/2+200, paint); // drow rectangle
canvas.translate(width/2+100, height/2+100);  // move origin of canvas to the center of the rectangle
canvas.rotate(45);  // canvas is roteted around the origine that is the center of the rectangle also. As a result, rectangle is roteted around its center.
canvas.translate(-(width/2+100), -(height/2+100));  // restore origin of canvas at original position
canvas.restore();
相关问题