我有兩個圖像,如下面的XAML代碼解釋:如何測試一個圖像是否在WPF的另一個上?
<Window x:Class="TestApplicationGestureKinect.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="768" Width="1024" ScrollViewer.VerticalScrollBarVisibility="Disabled" MinWidth="1024" MaxWidth="1024" MinHeight="768" MaxHeight="768">
<Grid Background="Black">
<Image x:Name="img1" HorizontalAlignment="Left" Margin="47,82,0,0" VerticalAlignment="Top" Source="photos/01.jpg" Height="200" RenderTransformOrigin="0.5,0.5" >
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="9.577"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<Image x:Name="cursorRight" HorizontalAlignment="Left" Margin="757,133,0,0" Width="48" Height="48" VerticalAlignment="Top" Source="cursors/right_open.png" />
</Grid>
</Window>
而下面的圖像顯示了這一顯示:
我需要一種方法來測試,從C#代碼如果名爲cursorRight
的圖像位於名爲img1
的圖像所覆蓋的區域上,則轉換後。
我該怎麼辦?我想到了兩個圖像邊框的一些考慮,但是對於cursorRight
圖像,考慮邊界框可能是可以接受的,但這對於其他圖像來說似乎不是一個好選擇......
編輯:下圖顯示的我多麼想做到四個例子:
光標在圖像上:
光標在圖像上:
SOLUTION:以下代碼是我在爲了解決上述問題使用。我考慮了光標的邊界框,而不是它的確切形狀。
private bool isOn(Image img1, Image img2)
{
if (img1 == null || img1.Visibility != System.Windows.Visibility.Visible)
{
return false;
}
double img1_topLeft_X = img1.Margin.Left;
double img1_topLeft_Y = img1.Margin.Top;
double img1_bottomRight_X = img1_topLeft_X + img1.Width;
double img1_bottomRight_Y = img1_topLeft_Y + img1.Height;
Point img1_topLeft = new Point(img1_topLeft_X, img1_topLeft_Y);
Point img1_bottomRight = new Point(img1_bottomRight_X, img1_bottomRight_Y);
HitTestResult result_topLeft = VisualTreeHelper.HitTest(img2.Parent as Grid, img1_topLeft);
HitTestResult result_bottomRight = VisualTreeHelper.HitTest(img2.Parent as Grid, img1_bottomRight);
if (result_topLeft != null && result_bottomRight != null)
{
if (result_topLeft.VisualHit.GetType() == typeof(Image) && result_bottomRight.VisualHit.GetType() == typeof(Image) &&
(result_topLeft.VisualHit as Image).Name.Equals(img2.Name) && (result_bottomRight.VisualHit as Image).Name.Equals(img2.Name))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
但是,以這種方式,只有當圖像的邊界框完全放到圖像上時,光標纔會在圖像上。這不完全是我所需要的,但由於它工作得很好,我決定使用這種方法。
不確定它是否可以工作,所以我將它添加爲註釋:嘗試在懸停時發射一個事件(IsMouseOver),如果您有多個圖像將事件連接到相同的方法 – Aviatrix 2013-04-27 17:45:30