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 canvas 中绘制的矩形?

4

2 回答 2

10

请用

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

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

于 2012-10-24T12:37:58.983 回答
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);

问题是整个画布正在旋转以旋转文本。所以我只需要在画布旋转后绘制矩形。

于 2012-10-24T12:36:33.680 回答