我有两个图像,如以下 XAML 代码中所述:
<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
图像来说,考虑边界框是可以接受的,这对于另一幅图像来说似乎不是一个好的选择……
编辑:以下图片显示了我想要做的四个示例:
光标在图像上:
光标不在图像上:
解决方案:以下代码是我用来解决上述问题的代码。我考虑了光标的边界框而不是它的确切形状。
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;
}
}
但是,以这种方式,只有当光标的边界框完全位于图像上时,光标才会位于图像上。这不完全是我所需要的,但由于它工作得很好,我决定使用这种方法。