我想學習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);
}
就我個人而言,我可能會完全按照您的「不那麼短而甜」的解決方案來做。我沒有遇到一個內置的庫,可以做到這一點。 – 2010-01-17 02:17:02