如何在画布上的鼠标单击位置添加节点
本文关键字:单击 鼠标 位置 添加 节点 | 更新日期: 2023-09-27 18:31:48
现在我是一个应用程序,允许用户单击按钮浏览图片以用作画布背景。我想做到这一点,如果用户单击画布上的某个位置,则会在该点放置一个节点。我假设我需要获取鼠标坐标。是否有一种简单的方法可以调用以将节点放置在鼠标单击位置,或者我是否必须遵循此链接中的路线:WPF - 使用鼠标事件在画布上绘图?提前谢谢。
编辑:添加了我尝试制作椭圆的代码。不过它不起作用,我不确定如何使用椭圆的鼠标单击坐标。我知道对于一行,它只是 .x1 = 当前点.x 等。
画布的 XAML 代码:
<Canvas Margin="0,45,2,8" x:Name="canvas1">
</Canvas>
用于制作画布背景的代码隐藏:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:''";
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(selectedFileName));
canvas1.Background = brush;
BitmapImage bitmap = new BitmapImage();
}
}
//This is the method for adding the ellipse.
private void addNode_MouseDown(object sender, MouseButtonEventArgs e)
{
Point currentPoint = new Point();
if (e.ButtonState == MouseButtonState.Pressed)
currentPoint = e.GetPosition(this);
Ellipse ellipse = new Ellipse();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0);
ellipse.Fill = mySolidColorBrush;
ellipse.Width = 10;
ellipse.Height = 10;
canvas1.Children.Add(ellipse);
}
想
通了。我不得不在我的addNode_MouseDown方法中使用它:
Canvas.SetLeft(ellipse, e.GetPosition(canvas1).X);
Canvas.SetTop(ellipse, e.GetPosition(canvas1).Y);
然后我只是在画布上订阅了它。