You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForms C#中FillPath异常合并AddArc:闭合曲线绘制失败求助

WinForms C# 闭合曲线图形填充异常修复方案

你的代码里有两个关键问题导致填充异常:

  1. 路径段的衔接顺序混乱,AddLine的起点没跟上一个路径的终点,FillPath填充时自动用直线连了错误的端点,出现多余填充区域。
  2. 底部弧线的参数设置不对,且整个路径未闭合,进一步加剧了异常。

给你修正后的代码:

Bitmap BitmapImage = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(BitmapImage);
SolidBrush solidBrush = new SolidBrush(Color.Purple);
Pen pen1 = new Pen(Color.Black, 2); // 假设你已定义该画笔

GraphicsPath myGraphicsPath = new GraphicsPath();

// 顶部左半圆:从(150,50)画到(100,50),向下弯曲
myGraphicsPath.AddArc(100, 50, 50, 50, 0, -180);
// 左侧竖线:从顶部半圆终点(100,100)向下到(100,200)
myGraphicsPath.AddLine(new Point(100, 100), new Point(100, 200));
// 底部横线:从(100,200)向右到(150,200)
myGraphicsPath.AddLine(new Point(100, 200), new Point(150, 200));
// 底部上半圆:从(150,200)向上画到(100,200),向上弯曲
myGraphicsPath.AddArc(100, 175, 50, 50, 180, -180);
// 右侧竖线:从底部半圆终点(150,175)向上到(150,50),衔接顶部半圆起点
myGraphicsPath.AddLine(new Point(150, 175), new Point(150, 50));

// 闭合路径(可选,最后一条线已连到起点,加上更稳妥)
myGraphicsPath.CloseFigure();

graphics.FillPath(solidBrush, myGraphicsPath);
graphics.DrawPath(pen1, myGraphicsPath);

// 释放GDI+资源,避免内存泄漏
solidBrush.Dispose();
pen1.Dispose();
graphics.Dispose();

修改说明

  • 理顺路径顺序:确保每个路径段的终点是下一段的起点,避免填充时自动乱连端点。
  • 修正底部弧线方向:把原来的0,180改成180,-180,让弧线方向正确,终点落在(150,175),刚好衔接右侧竖线。
  • 补上右侧竖线:原代码缺少这条关键线段,补上后路径完全闭合。
  • 添加资源释放:GDI+对象用完需手动释放,避免内存泄漏。

效果对比

预期图形:
预期图形

修正后你会得到和预期一致的图形,不会再出现异常填充。

内容的提问来源于stack exchange,提问作者Данил Филилеев

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:18:43