下面的示例代码...这将跟踪连续的鼠标移动以确定是否绘制了一个圆圈。每次触发 MouseMove 事件时,都会将光标 Point 添加到集合中,并启动计时器来评估集合并重置。
在评估集合时,它会首先确定中心Point,然后它会确保所有点都在距离中心一定距离内(在下图中的绿色区域内)并且在所有象限(一个完整的圆)。
使用简单的 WPF 窗口:
<Window x:Class="Shaping.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Canvas x:Name="ShapeCanvas" Background="Transparent" />
<Ellipse Width="100" Height="100" Stroke="Black" StrokeThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
还有一些乱七八糟的代码:
public partial class MainWindow : Window
{
List<Point> points;
Timer reset;
public MainWindow()
{
InitializeComponent();
points = new List<Point>();
reset = new Timer { AutoReset = false, Interval = 500 };
reset.Elapsed += (s, e) =>
{
App.Current.Dispatcher.BeginInvoke((Action)(() =>
{
ShapeCanvas.Children.Clear();
}));
if (points.Count > 10)
{
double? max_x = null;
double? min_x = null;
double? max_y = null;
double? min_y = null;
// evaulate points to determine center
foreach (var point in points)
{
max_x = Math.Max(max_x ?? point.X, point.X);
min_x = Math.Min(min_x ?? point.X, point.X);
max_y = Math.Max(max_y ?? point.Y, point.Y);
min_y = Math.Min(min_y ?? point.Y, point.Y);
}
var center = new Point((((double)max_x - (double)min_x) / 2) + (double)min_x, (((double)max_y - (double)min_y) / 2) + (double)min_y);
var count_r = 0;
var sum_r = 0d;
var all_r = new List<double>();
var quadrands = new int[4];
// evaluate points again to determine quadrant and to get all distances and average distance
foreach (var point in points)
{
// distance
var r = Math.Sqrt(Math.Pow(point.X - center.X, 2) + Math.Pow(point.Y - center.Y, 2));
sum_r += r;
count_r += 1;
all_r.Add(r);
// quadrand
quadrands[(point.Y > center.Y ? 1 : 0) + (point.X > center.X ? 2 : 0)] += 1;
}
var r_avg = sum_r / count_r;
if (all_r.Count(r => Math.Abs(r - r_avg) < r_avg * .3) >= count_r * .8 && quadrands.All(q => q > 1))
{
// you made a circle
App.Current.Dispatcher.BeginInvoke((Action)(() =>
{
ShapeCanvas.Children.Clear();
ShapeCanvas.Children.Add(new Ellipse() { Fill = new SolidColorBrush(Colors.Red), Width = 15, Height = 15 });
reset.Start();
}));
}
}
points.Clear();
};
ShapeCanvas.MouseMove += (s, e) =>
{
points.Add(e.GetPosition((Canvas)s));
reset.Stop();
reset.Start();
};
}
}
关于 quadrands.All(q=> q > 1) 的注意事项 -- 我最初是在检查所有象限 quadrants.All(q=> Math.Abs(q - avg_quad) < avg_quad * .3 之间的 均匀 分布,但这只有在以恒定速度绘制圆时(或者如果计数是根据速度调整;速度由连续点之间的距离决定)
.3 和 .8 只是我发现用来描述 roughly a circle 的数字——转换为:至少 80% 的点位于距中心平均距离的 +-15% 范围内。