繁体   English   中英

C#WPF在Image组件上绘制,MouseClick坐标

[英]C# WPF draw on Image component, MouseClick coordinates

我在C#WF中有一个应用程序,其中用户单击背景为.png的PictureBox并单击Click的坐标形状。 我正在使用GraphicsSystem.Drawing )和MouseCLick事件:

private void pictureBox1_MouseClick(object sender, MouseEventArgs e) {
    //some app logic
    Graphics g = pictureBox1.CreateGraphics();
    Brush brush = Brushes.Black;
    //some app logic, drawing looks like this
    g.FillRectangle(brush, e.X, e.Y, 10, 20);
}

我想在WPF中做同样的事情,但是我有几个问题:

  1. 在WPF中,没有PictureBox ,只有Image
  2. Image元素没有MouseClick事件
  3. WPF中不存在System.Drawing命名空间

我尝试使用Google,但只建立了如何绘制表格的方法,却找不到如何获取点击坐标,因此我的问题是:

  1. 如何获得点击Image元素的XY坐标? 正在保存坐标,稍后,我需要知道用户单击了backgroundimage的哪个像素。
  2. 如何在Image元素的XY坐标上绘制形状?
  3. 我应该使用Image还是有更好的组件? 我需要将.png图像保存在磁盘上作为背景。

谢谢。

多亏了bhmahler的链接,我才得到了缺少的信息,这是完整的绘图代码,以防万一有人需要它:

private void MyCanvasComponent_MouseDown(object sender, MouseButtonEventArgs e) {
    MyCanvasComponent.Children.Clear(); //removes previously drawed objects


    double x = e.GetPosition(MyCanvasComponent).X; //get mouse coordinates over canvas
    double y = e.GetPosition(MyCanvasComponent).Y;

    Ellipse elipsa = new Ellipse(); //create ellipse
    elipsa.StrokeThickness = 3;
    elipsa.Stroke = Brushes.Red;
    elipsa.Margin = new Thickness(x, y, 0, 0);      
    elipsa.Width = 20;
    elipsa.Height = 20;

    //add (draw) ellipse to canvas  
    MyCanvasComponent.Children.Add(elipsa);
}

背景图片的添加方式:

ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"Image1.png", UriKind.Relative));
MyCanvasComponent.Background = brush;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM