布局转换,找到相对点

时间:2013-07-19 12:01:07

标签: c# wpf point relative rect

我有一个画布(包含图像),我在其上应用LayoutTransform(ScaleTransform)。 我在此画布上绘制一个矩形(此矩形用于定义图像格式的导出区域)。 我想找到相对于画布的矩形坐标。实际上,ScaleTransforme用于缩放。我想制作一个导出区域的位图而不需要进行缩放(保持画布中图像的原始质量(分辨率))。

Xaml:

<Grid>
<Canvas x:Name="ExportAreaCanvas" 
        Panel.ZIndex="9999"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch">
    <Rectangle Stroke="Black" StrokeThickness="2" x:Name="ExportAreaRectangle"/>
</Canvas>


<Canvas x:Name="zoomControl" 
   HorizontalAlignment="Center" 
   VerticalAlignment="Center">
    <Canvas.LayoutTransform>
        <ScaleTransform ScaleX="{Binding CurrentZoom}"
                        ScaleY="{Binding CurrentZoom}" CenterX="0.5" CenterY="0.5"/>
    </Canvas.LayoutTransform>
    <Image x:Name="ImageToExport" Source="MySource"/>
<Canvas>

C#:

private RenderTargetBitmap GetZoneAsBitmap()
{
    Rect ZoneToExport = new Rect(Canvas.GetLeft(ExportAreaRectangle), Canvas.GetTop(ExportAreaRectangle), ExportAreaRectangle.Width, ExportAreaRectangle.Height);
    Point p1 = ExportAreaCanvas.TranslatePoint(new Point(Zone.X, Zone.Y), zoomControl);
    Point p2 = ExportAreaCanvas.TranslatePoint(new Point(Zone.Width, Zone.Height), zoomControl);

    Rect ZoneToExportFinal = new Rect(p1, new Size(p2.X, p2.Y));

    VisualBrush sourceBrush = new VisualBrush();
    sourceBrush.Visual = ImageToExport;
    sourceBrush.Stretch = Stretch.Fill;
    sourceBrush.Viewbox = ZoneToExportFinal;
    sourceBrush.ViewboxUnits = BrushMappingMode.Absolute;
    DrawingVisual drawingVisual = new DrawingVisual();
    using (DrawingContext drawingContext = drawingVisual.RenderOpen())
    {
        drawingContext.DrawRectangle(sourceBrush, null, ZoneToExportFinal);
        drawingContext.Close();
    }

    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)ZoneToExportFinal.Width, (int)ZoneToExportFinal.Height, 96, 96, PixelFormats.Default);
    renderTarget.Render(drawingVisual);
    return renderTarget;
}

最终图像根本不符合该区域。

0 个答案:

没有答案