C#图形库计算要绘制和画圆的范围和中点

时间:2019-02-12 14:46:13

标签: c# system.drawing

基本上我有一个菜单,用户选择要绘制的形状,然后用户单击两个点,在这两个点之间将绘制选定的形状。
我做了以这种方式计算的正方形

// 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);

但是我不知道如何以相同的方式绘制圆形和三角形

请告知,谢谢

3 个答案:

答案 0 :(得分:1)

以同样的方式。

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/

上链接对椭圆有帮助

答案 1 :(得分:0)

要绘制圆形,请使用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循环绘制所有线段(线)。

答案 2 :(得分:0)

如果用两个点((x1,y1),(x2,y2))指定圆的直径, 然后将DrawEllipse与x,y,w,h

一起使用

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

对于三角形,您确实需要三点。您可以将其限制为两点,就像指定直角三角形的斜边一样。但这还不够,因为有两个直角三角形可能具有该斜边,即上侧和下侧。你想要什么样的三角形?对,等,急性,等边,钝?