我使用以下代码
在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画布中绘制的矩形?
答案 0 :(得分:10)
请使用
canvas.save();
canvas.rotate();
//stuff to draw that should be rotated
canvas.restore();
否则你必须在之后补偿每次轮换
答案 1 :(得分: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);
事情是整个画布正在旋转以旋转文本。所以我只需要在画布旋转后绘制矩形。