C# 如何在XAML画布中绘制随机/不规则线?

C# 如何在XAML画布中绘制随机/不规则线?,c#,wpf,xaml,win-universal-app,C#,Wpf,Xaml,Win Universal App,我有一个XAML的画布,我想在其中使用C#绘制随机的不规则(手绘)线 这就是我想要的:HTML画布,但在XAMLC中# 我想把这条线画成水平线 Xaml: <Canvas Grid.Column="1" x:Name="ItemCanvas"></Canvas> 你可以用它来达到这个目的。它定义了接收和显示墨迹笔划的区域: <Grid> <InkCanvas Name="InkCanvas1"></InkCanvas> <

我有一个XAML的画布,我想在其中使用C#绘制随机的不规则(手绘)线

这就是我想要的:HTML画布,但在XAMLC中#

我想把这条线画成水平线

Xaml:

<Canvas Grid.Column="1" x:Name="ItemCanvas"></Canvas>
你可以用它来达到这个目的。它定义了接收和显示墨迹笔划的区域:

<Grid>
    <InkCanvas Name="InkCanvas1"></InkCanvas>
</Grid>

结果:


您需要为事件
MouseMove
MouseDown
MouseEnter
MouseUp
MouseLeave
添加方法。此外,当前位置和最后一个位置需要两个变量。如果还想撤消,则需要为此添加一个
堆栈。以下是所需的方法:

private void Canvas_MouseDown(Object sender, MouseButtonEventArgs e)
{
    // push start of line onto undo stack
    this.undo.Push(this.paintCanvas.Children.Count);
    this.last = e.GetPosition(this.paintCanvas);
}

private void Canvas_MouseMove(Object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (this.last.X != -1)
        {
            Point current = e.GetPosition(this.paintCanvas);
            Line l = new Line();
            l.X1 = this.last.X;
            l.Y1 = this.last.Y;
            l.X2 = current.X;
            l.Y2 = current.Y;
            l.Stroke = this.brush;
            l.StrokeThickness = this.thickness;
            this.paintCanvas.Children.Add(l);
            this.last = current;
        }
    }
}

private void Canvas_MouseUp(Object sender, MouseButtonEventArgs e)
{
    // push end of line onto undo stack
    this.undo.Push(this.paintCanvas.Children.Count);
}

private void Canvas_MouseLeave(Object sender, MouseEventArgs e)
{
    this.last = new Point(-1, -1);
}

private void Canvas_MouseEnter(Object sender, MouseEventArgs e)
{
   this.last = e.GetPosition(this.paintCanvas);
}
要从画布中删除最后一行,可以调用此
Undo
-方法:

private void Undo()
{
    if (this.undo.Count == 0)
        return;
    // pop indexes of last line (start index is one below top of stack)
    int to = this.undo.Pop();
    int from = this.undo.Pop();
    // remove last line from UIElement collection
    this.paintCanvas.Children.RemoveRange(from, to);
}
private void Undo()
{
    if (this.undo.Count == 0)
        return;
    // pop indexes of last line (start index is one below top of stack)
    int to = this.undo.Pop();
    int from = this.undo.Pop();
    // remove last line from UIElement collection
    this.paintCanvas.Children.RemoveRange(from, to);
}