在Android Canvas上绘图,角度不正确

时间:2017-06-06 09:02:12

标签: android canvas xamarin graphics2d

我有一个我为Android创建的自定义视图,我正在绘制一个圆形并将其分成几个部分。

以下是onDraw的代码:

int w = Width;
int h = Height;

int pl = PaddingLeft;
int pr = PaddingRight;
int pt = PaddingTop;
int pb = PaddingBottom;

int usableWidth = w - (pl + pr);
int usableHeight = h - (pt + pb);

int radius = Math.Min(usableWidth, usableHeight) / 2;
int cx = pl + (usableWidth / 2);
int cy = pt + (usableHeight / 2);

int lineLenght = radius - (pl * 2) - (pr * 2);

paint.Color = Color.Black;
paint.SetStyle(Paint.Style.Stroke);
canvas.DrawCircle(cx, cy, radius, paint);

//Move to top of the circle
float pointAngle = 360 / noOfJoints;
for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float x = cx + ((float)Math.Cos(radians(angle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(angle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}

但是当我运行它时,它提供了如下视图:

View Layout

哪个接近我想要的,但部分的开头应该是从中间开始的。如何让它从0角度开始(第一个分隔线应该是从上到下的直线)。

首选圆圈如下:

enter image description here

1 个答案:

答案 0 :(得分:3)

试试这个:

for (float angle = 0; angle < 361; angle = angle + pointAngle)
{   //move round the circle to each point
    float displacedAngle = angle - 90;
    float x = cx + ((float)Math.Cos(radians(displacedAngle)) * radius); //convert angle to radians for x and y coordinates
    float y = cy + ((float)Math.Sin(radians(displacedAngle)) * radius);
    canvas.DrawLine(cx, cy, x, y, paint); //draw a line from center point back to the point
}

角度0是圆圈的最右点,减去90将移动到顶点。

另外,建议在onDraw方法中尽可能避免变量创建和对象实例化。这是一个真正的性能杀手。