using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CircleGesture { public partial class Form1 : Form { private List points; private bool capturing; private bool isCircle; private Point centroid; private double radius; private double Distance( Point a, Point b ) { return Math.Sqrt((b.X - a.X) * (b.X - a.X) + (b.Y - a.Y) * (b.Y - a.Y)); } private bool isApproxCircle() { int k = points.Count; radius = 0; foreach (Point p in points) radius += Distance(centroid, p); radius /= k; const double eps = 0.35; // 35% difference to average is still ok. foreach (Point p in points) { double r = Distance(centroid, p); if (Math.Abs((radius-r)/radius)>eps) return false; } return true; } public Form1() { InitializeComponent(); points = new List(); } private void Form1_MouseDown(object sender, MouseEventArgs e) { points.Clear(); capturing = true; points.Add(e.Location); centroid.X = e.Location.X; centroid.Y = e.Location.Y; } private void Form1_MouseMove(object sender, MouseEventArgs e) { if (capturing) { points.Add(e.Location); centroid.X += e.Location.X; centroid.Y += e.Location.Y; } } private void Form1_MouseUp(object sender, MouseEventArgs e) { if (capturing) { points.Add(e.Location); centroid.X += e.Location.X; centroid.Y += e.Location.Y; centroid.X /= points.Count; centroid.Y /= points.Count; capturing = false; isCircle = isApproxCircle(); Invalidate(); } } private void Form1_Paint(object sender, PaintEventArgs e) { System.Drawing.Graphics graphicsObj = this.CreateGraphics(); Pen myPen = new Pen(System.Drawing.Color.Black, 2); int cnt = points.Count; if (cnt > 0) { Point[] pts = new Point[cnt]; for (int i = 0; i < cnt; ++i) { pts[i] = points[i]; graphicsObj.DrawLine(myPen, centroid, pts[i]); } graphicsObj.DrawPolygon(myPen, pts); if (isCircle) { Int32 r = Convert.ToInt32(radius); Rectangle myRectangle = new Rectangle(centroid.X - r, centroid.Y - r, 2*r, 2*r); graphicsObj.DrawEllipse(myPen, myRectangle); } } } } }