2009-11-05 66 views
6

我想學習WPF圖像源的座標,所以這裏有一個簡單的問題,我希望:將來自圖像控件在WPF

我有一個包含綁定到一個單獨的數據圖像元素的窗口與用戶可配置Stretch屬性

<Image Name="imageCtrl" Source="{Binding MyImage}" Stretch="{Binding ImageStretch}" /> 

當用戶在圖像上移動鼠標,我想相對於確定鼠標的座標到原始圖像對象(拉伸前/裁剪時所發生它顯示在控件中),然後用t做一些事情軟管座標(更新圖像)。

我知道我可以添加一個事件處理程序MouseMove事件在圖像控制,但我不知道如何才能最好變換座標:

void imageCtrl_MouseMove(object sender, MouseEventArgs e) 
{ 
    Point locationInControl = e.GetPosition(imageCtrl); 
    Point locationInImage = ??? 
    updateImage(locationInImage); 
} 

現在我知道我可以比較大小Source到控件的ActualSize,然後打開imageCtrl.Stretch來計算X和Y上的標量和偏移量,並自己進行轉換。但WPF已經擁有了所有的信息,這看起來像是可能內置於WPF庫的功能。所以我想知道:有沒有簡短而甜蜜的解決方案?或者我需要自己寫這個嗎?


編輯我追加我的電流,不那麼短期和甜的解決方案。它不是說不好,但我會有所驚訝,如果WPF沒有自動提供此功能:

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

就我個人而言,我可能會完全按照您的「不那麼短而甜」的解決方案來做。我沒有遇到一個內置的庫,可以做到這一點。 – 2010-01-17 02:17:02

回答

7

它可能會更容易,如果你使用的視框。例如:

<Viewbox Stretch="{Binding ImageStretch}"> 
    <Image Name="imageCtrl" Source="{Binding MyImage}" Stretch="None"/> 
</Viewbox> 

然後當你去調用GetPosition(..)時,WPF會自動計算縮放比例。

void imageCtrl_MouseMove(object sender, MouseEventArgs e) 
{ 
    Point locationInControl = e.GetPosition(imageCtrl); 
} 
+0

謝謝。我發現我不需要設置Horizo​​ntalAlignment,但將Image源的DPI設置爲96(我使用的是非標準位圖)非常重要。哦,'Viewbox'中的'b'是小寫字母:) – Gabriel 2010-08-27 06:29:59

+0

令人驚歎!這真是太棒了可以在WPF中輕鬆完成! 非常感謝,節省了我的時間。 – Fedor 2013-10-04 11:15:49