gpt4 book ai didi

c# - 如何在 XAML Canvas 中绘制随机/不规则线?

转载 作者:行者123 更新时间:2023-11-30 23:28:22 24 4
gpt4 key购买 nike

我有一个 XAML Canvas ,我想在其中使用 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;
}

最佳答案

您需要为事件添加方法MouseMove , MouseDown , MouseEnter , MouseUpMouseLeave .此外,您需要两个变量来表示当前位置和最后位置。如果您还想撤消,则需要添加 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);
}

要从 Canvas 中删除最后一行,您可以调用此 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);
}

关于c# - 如何在 XAML Canvas 中绘制随机/不规则线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36028763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com