2012-10-24 150 views
4

我使用下面的代码段如何在Android中旋转在画布上绘制的矩形?

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

这段代码使用文本旋转的护理借鉴Android的画布上的文字和它工作正常。我正在使用上面的代码在文本周围绘制一个蓝色矩形。现在我的问题是矩形不随文本旋转。它仍然是一样的。有什么办法来旋转在Android画布中绘制的矩形?

回答

2

我发现我自己的答案。我用下面的代码

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

的事情是整个画布旋转旋转文本。所以我只需要在画布旋转后绘制矩形。

+0

你是怎么计算的角度,因为我想在用户的触摸基础上旋转矩形 –

+0

嘿@NirmalPrajapat我偶然发现你的问题,有一个快速的答案,我可以给你从工作拷贝我已经做以前,希望它是有用的: Math.toDegrees(Math.atan2(Y - sdo.y,X - sdo.x))+ 40 ...其中x和y是触摸位置(我使用拖动手柄ov在图形上是erlay),sdo是旋转的位图,x和y是位图的中心,40常量是我的拖动手柄位于图形顶部的角度,即:起点。 – ZengoTim

+0

谢谢@ZengoTim,但我解决了:) –

10

请使用

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

否则你必须补偿每次旋转之后