我有两个图像,如下面的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