有一个画布(灰色),上面有图像(蓝色)。我对图像做了一些操作,想要在操作后找到图像的可见部分(红色)。
为此,我使用这种方法:
private double GetSquare()
{
Rect rect = GetBounds(Image, Canvas);
var canvasRect = RootGeometry.Rect;
canvasRect.Intersect(rect);
return canvasRect.Height * canvasRect.Width;
}
private static Rect GetBounds(FrameworkElement of, FrameworkElement from)
{
// Might throw an exception if of and from are not in the same visual tree
GeneralTransform transform = of.TransformToVisual(from);
return transform.TransformBounds(new Rect(0, 0, of.ActualWidth, of.ActualHeight));
}
XAML:
<Canvas Grid.Row="1" x:Name="ImageCanvas" Background="Gray">
<Canvas.Clip>
<RectangleGeometry x:Name="RootGeometry"/>
</Canvas.Clip>
<Image x:Name="Image" Stretch="Fill"
ManipulationStarted="OnManipulationStarted"
ManipulationDelta="OnManipulationDelta"
ManipulationCompleted="OnManipulationCompleted" Source="{...}"
ImageOpened="OnImageOpened">
<Image.RenderTransform>
<TransformGroup>
<MatrixTransform x:Name="previousTransform" />
<TransformGroup x:Name="currentTransform">
<ScaleTransform x:Name="scaleTransform" />
<RotateTransform x:Name="rotateTransform" />
<TranslateTransform x:Name="translateTransform" />
</TransformGroup>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Canvas>
该方法适用于二维图像。但是对于第3个图像,该方法返回不正确的结果。也许有人可以解释为什么方法会返回不正确的结果,并解释如何获取图像的可见部分(第3个)?