我当前的程序允许用户单击一个点,然后单击另一个点(至少20个像素)并在这两个点之间画一条线。我使用过折线,这样可以多次完成。虽然所有行的集合仅在完成所有点击后出现。
void DrawingCanvas_MouseUp(object sender, MouseButtonEventArgs e) {
Point position = e.GetPosition(this);
if (leftList == null) {
//starting a new set
leftList.Add(position);
lastPoint = position;
return;
}
//calculate distance, i.e. end click
double a = lastPoint.X - position.X;
double b = lastPoint.Y - position.Y;
double distance = Math.Sqrt(a * a + b * b);
if (distance > 20) {
//continue to add to list
leftList.Add(position);
lastPoint = position;
} else {
//end of the line
paint();
leftList = new PointCollection();
}
}
private void paint() {
Polyline line = new Polyline();
line.Visibility = System.Windows.Visibility.Visible;
line.StrokeThickness = 2;
line.Stroke = System.Windows.Media.Brushes.Black;
line.Points = leftList;
myCanvas.Children.Add(line);
}
所以我的问题是双重的:
A)如何制作,以便每次点击后立即添加新行。
B)如何在最后一个点和鼠标光标当前位置之间(即在您选择下一个点之前)之间渲染一条线
答案 0 :(得分:2)
以下简单示例在按下鼠标左键并且鼠标移动最小点距离20并且按下按钮时开始绘制新的折线。它以红色或绿色绘制最后一条折线段(到当前鼠标位置),具体取决于其长度。如果释放鼠标按钮并且新片段的长度>> 20,则将新点附加到折线。否则,折线终止,并且可以创建新的折线。
private Polyline polyline;
private Polyline segment = new Polyline { StrokeThickness = 2 };
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (polyline == null)
{
var canvas = (Canvas)sender;
var point = e.GetPosition(canvas);
// create new polyline
polyline = new Polyline { Stroke = Brushes.Black, StrokeThickness = 2 };
polyline.Points.Add(point);
canvas.Children.Add(polyline);
// initialize current polyline segment
segment.Stroke = Brushes.Red;
segment.Points.Add(point);
segment.Points.Add(point);
canvas.Children.Add(segment);
}
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (polyline != null)
{
// update current polyline segment
var canvas = (Canvas)sender;
segment.Points[1] = e.GetPosition(canvas);
var distance = (segment.Points[0] - segment.Points[1]).Length;
segment.Stroke = distance >= 20 ? Brushes.Green : Brushes.Red;
}
}
private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (polyline != null)
{
var canvas = (Canvas)sender;
segment.Points[1] = e.GetPosition(canvas);
var distance = (segment.Points[0] - segment.Points[1]).Length;
if (distance >= 20)
{
polyline.Points.Add(segment.Points[1]);
segment.Points[0] = segment.Points[1];
}
else
{
if (polyline.Points.Count < 2)
{
canvas.Children.Remove(polyline);
}
polyline = null;
segment.Points.Clear();
canvas.Children.Remove(segment);
}
}
}
答案 1 :(得分:0)
请在每次点击时保留一系列积分。在集合中,您可以添加一个类,它将具有两个属性,如StartPoint和EndPoint。
第一次单击鼠标时,只需将一个类对象添加到仅具有起点的集合中。 当您下次单击鼠标时,广告结束指向该类的最后一个对象,同时创建一个新对象并将此点指定为其起点,并在调用绘制函数后将其添加到集合中。