Note that there are some explanatory texts on larger screens.

plurals
  1. POTransforming coordinates from an image control to the image source in WPF
    text
    copied!<p>I'm trying to learn WPF, so here's a simple question, I hope:</p> <p>I have a window that contains an Image element bound to a separate data object with user-configurable <code>Stretch</code> property</p> <pre><code>&lt;Image Name="imageCtrl" Source="{Binding MyImage}" Stretch="{Binding ImageStretch}" /&gt; </code></pre> <p>When the user moves the mouse over the image, I would like to determine the coordinates of the mouse with respect to the <em>original image</em> (before stretching/cropping that occurs when it is displayed in the control), and then do something with those coordinates (update the image).</p> <p>I know I can add an event-handler to the MouseMove event over the Image control, but I'm not sure how best to transform the coordinates:</p> <pre><code>void imageCtrl_MouseMove(object sender, MouseEventArgs e) { Point locationInControl = e.GetPosition(imageCtrl); Point locationInImage = ??? updateImage(locationInImage); } </code></pre> <p>Now I know I could compare the size of <code>Source</code> to the <code>ActualSize</code> of the control, and then switch on <code>imageCtrl.Stretch</code> to compute the scalars and offsets on X and Y, and do the transform myself. But WPF has all the information already, and this seems like functionality that might be built-in to the WPF libraries somewhere. So I'm wondering: is there a short and sweet solution? Or do I need to write this myself?</p> <hr> <p><strong>EDIT</strong> I'm appending my current, not-so-short-and-sweet solution. Its not that bad, but I'd be somewhat suprised if WPF didn't provide this functionality automatically:</p> <pre><code>Point ImgControlCoordsToPixelCoords(Point locInCtrl, double imgCtrlActualWidth, double imgCtrlActualHeight) { if (ImageStretch == Stretch.None) return locInCtrl; Size renderSize = new Size(imgCtrlActualWidth, imgCtrlActualHeight); Size sourceSize = bitmap.Size; double xZoom = renderSize.Width / sourceSize.Width; double yZoom = renderSize.Height / sourceSize.Height; if (ImageStretch == Stretch.Fill) return new Point(locInCtrl.X / xZoom, locInCtrl.Y / yZoom); double zoom; if (ImageStretch == Stretch.Uniform) zoom = Math.Min(xZoom, yZoom); else // (imageCtrl.Stretch == Stretch.UniformToFill) zoom = Math.Max(xZoom, yZoom); return new Point(locInCtrl.X / zoom, locInCtrl.Y / zoom); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload