Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing on an Android Canvas, angle is not correct

I have a custom view that I have created for Android where I am drawing a Circle and dividing it into sections.

Here is the code for 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
}

But when I run this, it provides a view like the following:

View Layout

Which is close to what I want, but the start of sections should be from the middle. How can I get it to start from 0 angle (first divider should be from Top to bottom straight line).

The preferred circle is as follows:

enter image description here

like image 836
progrAmmar Avatar asked Jan 03 '23 22:01

progrAmmar


1 Answers

Try this:

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
}

Angle 0 is the rightest point of the circle, subtracting 90 will it move to top point.

Also, a recommendation, avoid variable creation and object instantiation as much as possible in the onDraw method. It's a real performance killer.

like image 110
Sergi and Replace Avatar answered Jan 15 '23 19:01

Sergi and Replace