如何在Android中使用canvas旋转文本

dev*_*oid 5 android canvas path geometric-arc

我在android中绘制了一个使用canvas的饼图,并使用下面的代码我在该饼图的每个切片上绘制一个文本(在路径上绘制弧),现在我想要明智地绘制文本,即从每个中心到末尾切片,所以如何使用开始和扫掠角度旋转圆弧.

p.addArc(mEventsRect, fStartAngle, fSweepAngle);
mBgPaints.setColor(iTextColor);
canvas.drawTextOnPath(sTextValue, p, fHOffSet, fVOffSet, mBgPaints);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 7

您已经有了文本的 x 和 y,使用它们来旋转画布

canvas.rotate(yourDegrees, x, y)
canvas.drawText(yourText, x, y, yourPaint)
canvas.rotate(-yourDegrees, x, y)
Run Code Online (Sandbox Code Playgroud)

负号否定第一次旋转。您可以交换它以沿相反方向旋转。

您可以在循环中执行此操作,但每次坐标更改时都必须完成旋转循环。


Waz*_*_Be 6

你可以尝试这个片段:(来自:http://www.helloandroid.com/tutorials/how-use-canvas-your-android-apps-part-2)

int x = 75;
int y = 185;
paint.setColor(Color.GRAY);
paint.setTextSize(25);
String rotatedtext = "Rotated helloandroid :)";

//Draw bounding rect before rotating text:

Rect rect = new Rect();
paint.getTextBounds(rotatedtext, 0, rotatedtext.length(), rect);
canvas.translate(x, y);
paint.setStyle(Paint.Style.FILL);

canvas.drawText(rotatedtext , 0, 0, paint);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(rect, paint);

canvas.translate(-x, -y);


paint.setColor(Color.RED);
canvas.rotate(-45, x + rect.exactCenterX(),y + rect.exactCenterY());
paint.setStyle(Paint.Style.FILL);
canvas.drawText(rotatedtext, x, y, paint);
Run Code Online (Sandbox Code Playgroud)

  • 我想它会是这样的:centerOfCircle+radius*cos(angleOfThePie)/2 (2认同)