簡體   English   中英

c#繪圖庫計算繪制和圓形的范圍和中點

[英]c# drawing library calculate ranges and midpoints to draw and circle

基本上我有一個菜單,用戶選擇想要繪制的形狀,然后用戶點擊兩個點,在這兩個點之間將繪制所選的形狀。
我做了以這種方式計算的 Square

// calculate ranges and mid points
xDiff = oppPt.X - keyPt.X;
yDiff = oppPt.Y - keyPt.Y;
xMid = (oppPt.X + keyPt.X) / 2;
yMid = (oppPt.Y + keyPt.Y) / 2;

// draw square
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y,
    (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2));
g.DrawLine(blackPen, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2),
    (int)oppPt.X, (int)oppPt.Y);
g.DrawLine(blackPen, (int)oppPt.X, (int)oppPt.Y,
    (int)(xMid - yDiff / 2), (int)(yMid + xDiff / 2));
g.DrawLine(blackPen, (int)(xMid - yDiff / 2),
    (int)(yMid + xDiff / 2), (int)keyPt.X, (int)keyPt.Y);

但我不知道如何以同樣的方式繪制圓形和三角形

請指教,謝謝

要繪制圓,請使用g.DrawEllipse ,這是一個很好的擴展方法:

public static void DrawCircle(Graphics g, Pen pen, float centerX, float centerY, float radius)
{
    g.DrawEllipse(pen, centerX - radius, centerY - radius, radius + radius, radius + radius);
}

要繪制填充,只需將DrawEllipse更改為FillElipse並將Pen更改為Brush

public static void DrawCircleFilled(Graphics g,  Brush brush, float centerX, float centerY, float radius)
{
    g.FillEllipse(brush, centerX - radius, centerY - radius, radius + radius, radius + radius);
}

如果您堅持只用線條繪制形狀,請不要害怕。 一個三角形只是用三條線畫出來的,這很容易,所以我不會在這里寫。 至於一個圓圈:

圓由若干段組成,段數越多,圓的質量越好。 你可以從一個簡單的三角形開始,然后再添加一條線,你就有了一個正方形,然后是五邊形、六邊形等等。 每條線的形狀在視覺上更像是一個圓形。

如您所見,每條線覆蓋了 (360 / N) 的總角度。 所以你可以使用for循環來繪制所有的線段(線)。

同路。

int left = 20, top = 20
int right = 100, bot = 100;

// triangle
g.DrawLine(Pens.Red, left, bot, right, bot);
g.DrawLine(Pens.Red, right, bot, left + (right-left) / 2 /* was miss calc */, top);
g.DrawLine(Pens.Red, left + (right - left) / 2, top, left, bot);  // better looks
//g.DrawLine(Pens.Red, left, bot, left + (right-left) / 2 /* was miss calc */, top);

// circle
int len = (right - left) / 2;
int centerX = left + (right - left) / 2, centerY = top + (bot - top) / 2;
for (int i = 0; i <= 360; i++)
{
    int degrees = i;
    double radians = degrees * (Math.PI / 180);

    int x = centerX + (int)(len * Math.Cos(radians));
    int y = centerY + (int)(len * Math.Sin(radians));
    e.Graphics.FillRectangle(Brushes.Red, x, y, 1, 1); // single pixel drawing
}

但是橢圓更難

http://www.petercollingridge.co.uk/tutorials/computational-geometry/finding-angle-around-ellipse/

上鏈接是 Ellipse 的幫助

如果您用兩個點((x1,y1),(x2,y2)) 指定圓的直徑,則使用帶有 x,y,w,h 的DrawEllipse

x = cx-r

y = cy-r

d = w = h = sqrt((x2-x1)^2+(y2-y1)^2)

在哪里

cx = |x2-x1|/2

cy = |y2-y1|/2

r = d/2

對於三角形,您確實需要三個點。 您可以將其限制為兩點,如指定直角三角形的斜邊。 但這仍然不夠信息,因為有兩個直角三角形可能有斜邊,即上邊和下邊。 你想要什么樣的三角形? 對,iso,銳角,等邊角,鈍角?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM