Search code examples
c#wpfxamlwin-universal-app

How to draw random/irregular line in XAML canvas?


I have a canvas in XAML in which I want to draw random irregular (Hand drawn) line using C#.

This is what I want: http://jsfiddle.net/GfGVE/9/ HTML Canvas but in XAML C#

I want the line to be drawn Horizontally.

Xaml:

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

C#:

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

Solution

  • You need to add methods for the events MouseMove, MouseDown, MouseEnter, MouseUp and MouseLeave. Additionally you need two variables for the current position and the last position. If you also want to undo you need to add a Stack<int> for this. These are the needed methods:

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

    To remove the last line from your canvas you can call this 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);
    }