2016-03-16 29 views

回答

1

您需要添加方法的事件MouseMoveMouseDownMouseEnterMouseUpMouseLeave。附加地,你需要兩個變量來表示當前位置和最後一個位置。如果您還想撤消,則需要爲此添加Stack<int>。這些都是需要的方法:

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

您可以使用InkCanvas用於此目的。它定義了接收和顯示墨水筆劃面積:

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

結果:

enter image description here