我想在表单上绘制一个多边形,但我想通过鼠标点击添加多边形位置。
现在我给了常量(x,y)位置并且它返回了一个多边形,但是我想通过点击鼠标来添加这些位置。
Point[] po = new Point[]
{
new Point {X=15, Y=51},
new Point {X=40, Y= 13},
new Point {X=87, Y= 53},
new Point {X=56, Y= 87},
new Point {X=44, Y= 32},
};
答案 0 :(得分:0)
为绘制多边形创建自定义控件:
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class DrawPolygon : Control
{
ObservableCollection<PointF> points;
public int SideCount
{
get { return sideCount; }
set { sideCount = value; }
}
public DrawPolygon()
{
InitializeComponent();
points = new ObservableCollection<PointF>();
points.CollectionChanged += Points_CollectionChanged;
}
private void Points_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
if (points.Count >= sideCount)
{
points = new ObservableCollection<PointF>(points.Skip(points.Count - sideCount));
points.CollectionChanged += Points_CollectionChanged;
}
Refresh();
}
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
points.Add(e.Location);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (points.Count > 1)
pe.Graphics.DrawPolygon(Pens.Aqua, points.ToArray());
}
}
}
构建完成后,您可以将其从工具箱添加到表单中。
这是结果的示例:Polygon