【问题标题】:Drawing a polygon on the form在窗体上绘制多边形
【发布时间】:2017-01-25 07:49:46
【问题描述】:

我想在表单上绘制一个多边形,但我想通过鼠标单击添加多边形位置。

现在我给定了 (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},
            };

【问题讨论】:

  • 有很多问题和资源可用于接收鼠标点击。你已经尝试了什么?您是否真的试图找到解决方案?你用的是winforms还是wpf?
  • 这是一个示例代码,我认为这可以帮助您。 stackoverflow.com/questions/12108534/…
  • 我尝试让用户通过鼠标点击来绘制一个多边形,我会用它来确定@Ben 表单上的感兴趣区域
  • 使用鼠标点击并收集列表中的 e.Locations!使用 Paint 事件来 e.Graphics.DrawPolygon(Pens.black, yourList.ToArray());
  • @Tom:该链接集中收集点并将它们绘制到同一个(Paint)事件中。这是无稽之谈,因为问题确实要求提供交互式解决方案。 - 相反,前者进入 MouseClick 并且只绘制到 Paint 事件中。

标签: c# drawing polygons


【解决方案1】:

为绘制多边形创建自定义控件:

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

【讨论】:

  • 听起来有点矫枉过正,但仍然不允许重叠多边形。 Polygon 类似乎更合适。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
相关资源
最近更新 更多