【发布时间】:2014-11-24 23:45:48
【问题描述】:
现在我有一个应用程序,它允许用户单击一个按钮来浏览用作画布背景的图片。我想这样做,如果用户单击画布上的某个位置,则会在该点放置一个节点。我假设我需要获取鼠标坐标。是否有一种简单的方法可以调用将节点放置在鼠标单击位置,或者我是否必须走此链接中的路线:WPF - Drawing on canvas with mouse events?提前致谢。
编辑:添加了我试图制作椭圆的代码。但是它不起作用,我不确定如何使用鼠标单击的坐标和椭圆。我知道一行只是 .x1 = currentPoint.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);
}
【问题讨论】:
-
鼠标位置为
Mouse.GetPosition()。Canvas内部的定位是通过Canvas.Left等设置的。node是什么?是simple visual吗? -
哦,对不起,我所说的节点只是一个小圆圈,我会设置它的大小和颜色以及所有这些东西。我现在正在使用椭圆,直到我可以让它正常工作。我将更新帖子以显示我尝试过的代码。
-
这里的代码展示了如何做到这一点顺便说一句stackoverflow.com/questions/27075815/…
标签: c# wpf xaml wpf-controls mouseevent