1

I am trying to draw a rectangle on top of an image when I hold right click and move the mouse across the image. At the moment of the mouse click a boolean is changed to true and when the mouse move event occurs and the bool is true, I have the next code:

            // currMouselocation - the current mouse location rightClickTrackLocation - the point where the user right clicked
            trackRect.Visibility = Visibility.Visible;//making the rectangle visible
            var xPos = Math.Min(currMouselocation.X, rightClickTrackLocation.X);
            var yPos = Math.Min(currMouselocation.Y, rightClickTrackLocation.Y);
            var w = Math.Max(currMouselocation.X, rightClickTrackLocation.X) - xPos;
            var h = Math.Max(currMouselocation.Y, rightClickTrackLocation.Y) - yPos;
            trackRect.Width = w;
            trackRect.Height = h;

            Canvas.SetLeft(trackRect, xPos);
            Canvas.SetTop(trackRect, yPos);

The problem is that the Rectangle is drawn from the center of the image and not from the clicked point.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
Roizman
  • 11
  • 4
  • type error, they are - xPos and yPos – Roizman Dec 31 '14 at 14:49
  • This code seems right. Do you get the mouse position relative to the same element? – nkoniishvt Dec 31 '14 at 15:02
  • Tried it and it works well. Is your Rectangle inside a Canvas? Because if it's not the Canvas.SetLeft and SetTop are useless – nkoniishvt Dec 31 '14 at 15:07
  • Yes I do, and where ever i start the pull from, the rectangle is always drawn from the center of the image – Roizman Dec 31 '14 at 15:08
  • @Roizman show us your XAML & how you get the mouse position because I copy/pasted your code and it works as intended and your problem seems like an alignment problem (which can't occur in a Canvas) – nkoniishvt Dec 31 '14 at 15:08
  • Make sure that trackRect is actually a child of a Canvas. Otherwise setting Left and Top would have no effect. – Clemens Dec 31 '14 at 15:43
  • http://stackoverflow.com/questions/16434356/draw-rectangle-when-mouse-dragged-using-mvvm-in-wpf?rq=1 – Gilad Dec 31 '14 at 15:52

0 Answers0