Home > Back-end >  How do I convert from mouse coordinates to pixel coordinates of a TransformedBitmap embedded in a la
How do I convert from mouse coordinates to pixel coordinates of a TransformedBitmap embedded in a la

Time:11-24

Similar to enter image description here

This is important because I'm trying to allow the user to select an ROI, and I need to know when the selection is beyond the image bounds, though I still want to allow it.

CodePudding user response:

You may perform the transformation on a "test point" inside the image bounds (e.g. the center) and the modulo operation on the transformed test point. Then use the offset between the transformed test point and the adjusted (by modulo) test point to adjust the actual point.

var p = e.GetPosition(TheImage);

p = new Point(
    p.X * bs.PixelWidth / TheImage.ActualWidth,
    p.Y * bs.PixelHeight / TheImage.ActualHeight);

if (TheImage.Source is TransformedBitmap tb)
{
    var inverse = tb.Transform.Value;
    inverse.Invert();
    inverse.OffsetX = 0.0;
    inverse.OffsetY = 0.0;

    var w = tb.Source.PixelWidth;
    var h = tb.Source.PixelHeight;

    var v = new Vector(bs.PixelWidth / 2, bs.PixelHeight / 2); // test point
    var v1 = inverse.Transform(v); // transformed test point
    var v2 = new Vector((v1.X   w) % w, (v1.Y   h) % h); // adjusted

    p = inverse.Transform(p) - v1   v2; // add adjusting offset
}

TheLabel.Content = $"x: {p.X:F2}, y: {p.Y:F2}";
  • Related