简体   繁体   中英

Drawing a polygon on the form

I would like to draw a polygon on the form but i would like to add polygon positions by mouse click.

Right now i gave the constant (x,y) positions and it returns me a polygon,But i would like to add those position by clicking mouse.

 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},
            };

create a customcontrol for draw Polygon:

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());

    }
}

}

After build, you can add it from toolbox to your form.

This is a sample of result: Polygon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM