【问题标题】:Drawing on an Android Canvas, angle is not correct在 Android Canvas 上绘图,角度不正确
【发布时间】:2017-06-06 17:08:05
【问题描述】:

我有一个为 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
}

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

这与我想要的很接近,但部分的开始应该从中间开始。我怎样才能让它从 0 角度开始(第一个分隔线应该是从上到下的直线)。

首选圆圈如下:

【问题讨论】:

    标签: android canvas xamarin graphics2d


    【解决方案1】:

    试试这个:

    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方法中尽量避免变量创建和对象实例化。这是一个真正的性能杀手。

    【讨论】:

    • 谢谢,我认为 0 角应该在顶部。感谢及时回复
    猜你喜欢
    • 2012-06-11
    • 2014-02-23
    • 2012-05-05
    • 2021-04-02
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多