2017-06-06 70 views
3

我有一個自定義視圖,我爲Android創建了一個繪製圓並將其劃分爲多個部分的地方。在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

這是接近我想要的,但部分的開始應該從中間開始。我怎樣才能從零角度開始(第一個分頻器應該是從上到下的直線)。

優選圓如下:

enter image description here

回答

2

嘗試這種情況:

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

謝謝,我認爲0角應該在上面。感謝您的及時回覆 – progrAmmar