【问题标题】:How to draw random/irregular line in XAML canvas?如何在 XAML 画布中绘制随机/不规则线?
【发布时间】:2016-03-16 07:01:39
【问题描述】:

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

这就是我想要的:http://jsfiddle.net/GfGVE/9/ HTML Canvas 但在 XAML C# 中

我希望水平线绘制。

Xaml:

<Canvas Grid.Column="1" x:Name="ItemCanvas"></Canvas>

C#:

public ItemControl()
{
    this.InitializeComponent();
    canvas = this.ItemCanvas;    
}

【问题讨论】:

    标签: c# wpf xaml win-universal-app


    【解决方案1】:

    您需要为事件MouseMoveMouseDownMouseEnterMouseUpMouseLeave 添加方法。此外,您需要两个变量来表示当前位置和最后一个位置。如果您还想撤消,则需要为此添加Stack&lt;int&gt;。这些是需要的方法:

    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-method:

    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);
    }
    

    【讨论】:

      【解决方案2】:

      您可以为此目的使用InkCanvas。它定义了一个接收和显示墨水笔划的区域:

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

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        相关资源
        最近更新 更多