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

标签 android canvas xamarin graphics2d

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

这是 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 :

View Layout

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

首选圈子如下:

enter image description here

最佳答案

试试这个:

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

关于android - 在 Android Canvas 上绘图,角度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385723/

相关文章:

java - onClick 在 ListActivity 中使用 SimpleCursorAdapter

image - 在 Canvas html5上导入图像

javascript - 为什么 context.restore() 不会将上下文的比例设置回 (1, 1)?

c# - Xamarin PCL C# - 将字符串反序列化为 JSONObject/JSONArray

安卓首选项 : Incorrect default values DESPITE "setDefaultValues"

android - 如何在 Android 中使用 Camera2 API 录制视频时以编程方式拍摄照片

java - 'finally'如何阻止android运行

javascript - Canvas 动画运行不流畅。我能做些什么?

xaml - ScrollView 中的 Xamarin Center StackLayout

ios - 如何在 ios 的 Xamarin 谷歌地图组件中处理点击事件