C#用GraphicsPath绘制圆形,其中部分被切除

5

我正在尝试用三个参数画出以下形状:

  • 半径
  • 中心点
  • 切除长度

切除部分是圆的底部。

enter image description here

我想到了可以使用

var path = new GraphicsPath();
path.AddEllipse(new RectangleF(center.X - radius, center.Y - radius, radius*2, radius*2))
// ....
g.DrawPath(path);

但是,我该如何画出这样的东西呢?

顺便问一下,那个形状的名字是什么?由于缺乏术语,我无法搜索以前的问题或其他内容。

谢谢。


你对这一个或两个解决方案感到满意吗?还是仍然存在问题? - TaW
3个回答

6

请将以下代码放入绘制事件中:

// set up your values
float radius = 50;
PointF center = new Point( 60,60);
float cutOutLen = 20;

RectangleF circleRect = 
           new RectangleF(center.X - radius, center.Y - radius, radius * 2, radius * 2);

// the angle
float alpha = (float) (Math.Asin(1f * (radius - cutOutLen) / radius) / Math.PI * 180);

var path = new GraphicsPath();
path.AddArc(circleRect, 180 - alpha, 180 + 2 * alpha);
path.CloseFigure();

e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.FillPath(Brushes.Yellow, path);
e.Graphics.DrawPath(Pens.Red, path);

path.Dispose();

这是结果:

切圆

我不确定“cut circle”这个词的意思,实际上它是一个“Thales Circle”(塞勒斯圆)。


4

谢谢。还有一件事。我能否获得弧和线相交的位置?这个信息对我很有用。 - Joonhwan
尝试实现后,我意识到需要使用正弦/余弦数学函数。是否有其他方法可以做到这一点?例如,从圆形中减去矩形或其他什么东西。 - Joonhwan
你可以尝试使用Region.Xor http://msdn.microsoft.com/en-us/library/awbdfdhf(v=vs.110).aspx 抱歉,我现在无法发布或检查任何代码。 - Denis Palnitsky
我认为应该是Region.Exclude(rectangle); 但那只对填充有用... - TaW
这比复制粘贴的答案更有效。 - Galacticai

0

这是我实现的一个绘制所需图形的方法:

    void DrawCutCircle(Graphics g, Point centerPos, int radius, int cutOutLen)
    {
        RectangleF rectangle = new RectangleF(
                        centerPos.X - radius,
                        centerPos.Y - radius,
                        radius * 2,
                        radius * 2);

        // calculate the start angle
        float startAngle = (float)(Math.Asin(
            1f * (radius - cutOutLen) / radius) / Math.PI * 180);

        using (GraphicsPath path = new GraphicsPath())
        {
            path.AddArc(rectangle, 180 - startAngle, 180 + 2 * startAngle);
            path.CloseFigure();

            g.FillPath(Brushes.Yellow, path);
            using (Pen p = new Pen(Brushes.Yellow))
            {
                g.DrawPath(new Pen(Brushes.Blue, 3), path);
            }
        }
    }

您可以在控件中按以下方式使用它:

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        DrawCutCircle(e.Graphics, new Point(210, 210), 200, 80);
    }

这就是它的样子:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接