0

I have an app in C# WF, where user clicks on PictureBox with .png image at background and on click's coordinates shape is drawed. I'm using Graphics (System.Drawing) and MouseCLick event:

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

I want to do the same in WPF, but I have few problems:

  1. In WPF, there is no PictureBox, just Image
  2. Image element has no MouseClick event
  3. System.Drawing namespace doesn't exist in WPF

I tried to Google, but I founded only how to draw on form and I couldn't find how to get coordinates of click, so my questions are:

  1. How to get XY coordinates of click on Image element? Coordinates are being saved, later, I need to know, on which pixel of backgroundimage user clicked.
  2. How to draw shape on XY coordinates of Image element?
  3. Should I use Image, or is there any better component? I need to have .png image saved on disk as background.

Thanks.

Adam Ježek
  • 464
  • 5
  • 15

2 Answers2

1

Looks like you can achieve what you are looking to do with an InkCanvas

Draw on image control in WPF

https://msdn.microsoft.com/en-us/library/system.windows.controls.inkcanvas(v=vs.110).aspx

For mouse position, please see WPF Mouse down event no Coordinates

Community
  • 1
  • 1
hawkstrider
  • 4,141
  • 16
  • 27
0

Thanks to links from bhmahler, I got the missing info, here's the complete drawing code in case someone will need it:

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

background image added simply by:

ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"Image1.png", UriKind.Relative));
MyCanvasComponent.Background = brush;
Adam Ježek
  • 464
  • 5
  • 15