1、问题描述
c#中,希望用鼠标点击事件,实现多边形的绘制;
2、解决思路
a、创建一个链表,将鼠标左键选中的点存储到链表中;
b、根据链表中的值,利用c#的DrawPolygon()函数绘制;
3、核心代码
List<Point> polyPoints = null;
bool cliceMenu = true;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (cliceMenu)
{
if (e.Button == MouseButtons.Left)
{
if (polyPoints == null) polyPoints = new List<Point>();
polyPoints.Add(e.Location);
}
else if (e.Button == MouseButtons.Right&&polyPoints!=null)
{
//Pen pen = new Pen(Color.Red, 3);
//这个是在picturebox控件中创建的图形
using (var g = pictureBox1.CreateGraphics())
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(pictureBox1.BackColor);
//填充多边形
//using (SolidBrush br = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
//{
// g.FillPolygon(br, polyPoints.ToArray());
//}
if (polyPoints.ToArray().Length >= 3)
{
//绘制轮廓
g.DrawPolygon(Pens.Red, polyPoints.ToArray());
//绘制顶点
foreach (Point p in polyPoints)
{
g.FillEllipse(Brushes.Red, new Rectangle(p.X - 2, p.Y - 2, 4, 4));
}
}
polyPoints = null;
}
}
}
}
参考: