以下是示例代码... 这将跟踪连续的鼠标移动以确定是否绘制了一个圆。每次MouseMove事件触发时,光标
Point
将被添加到一个集合中,并启动计时器来评估集合并重置。
在评估集合时,它将首先确定中心
Point
,然后确保所有点都在与中心的一定距离内(在下面的图像中的绿色区域内),并且在所有象限中都有点 (一个
完整的圆)。
![enter image description here](https://istack.dev59.com/UxSBA.webp)
使用一个简单的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;
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];
foreach (var point in points)
{
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);
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))
{
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
只是我找到的描述
大致为圆形
的数字--转换为:至少80%的点落在中心平均距离的+-15%范围内。