WPF绘图---Canvas中Polygon屏幕居中显示

问题描述

在一个Canvas中绘制了多个Polygon,由于坐标可能超出界面显示范围,需要将绘制的Polygon居中显示,并且缩放至界面大小,效果如下:

xaml代码
xml 复制代码
<Border
    x:Name="border"
    Background="#fff"
    ClipToBounds="True">
    <Canvas
        x:Name="canvas"
        Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType=Border}}"
        Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource AncestorType=Border}}">
        <Canvas.RenderTransform>
            <TransformGroup />
        </Canvas.RenderTransform>
    </Canvas>
</Border>
实现代码
csharp 复制代码
private void CenterAndScalePolygons()
{
    if (canvas == null || canvas.Children.Count == 0)
    {
        return;
    }
    // 获取所有 Polygon 的边界框
    Rect boundingBox = GetBoundingBox(canvas.Children.OfType<Polygon>());

    // 计算需要进行的缩放和平移操作
    double scaleX = border.ActualWidth / boundingBox.Width;
    double scaleY = border.ActualHeight / boundingBox.Height;

    // 使用较小的缩放比例,保持图形完全在 Canvas 内显示
    double scale = Math.Min(scaleX, scaleY);

    double offsetX = border.ActualWidth / 2 - (boundingBox.Left + boundingBox.Right) / 2 * scale;
    double offsetY = border.ActualHeight / 2 - (boundingBox.Top + boundingBox.Bottom) / 2 * scale;

    // 遍历 Polygon 进行缩放和平移
    foreach (var polygon in canvas.Children.OfType<Polygon>())
    {
        ScaleTransform scaleTransform = new ScaleTransform(scale, scale);
        TranslateTransform translateTransform = new TranslateTransform(offsetX, offsetY);

        TransformGroup transformGroup = new TransformGroup();
        transformGroup.Children.Add(scaleTransform);
        transformGroup.Children.Add(translateTransform);

        polygon.RenderTransform = transformGroup;
        // 调整 Polygon 边框线宽
        polygon.StrokeThickness = 1 / scale;
    }
}

private Rect GetBoundingBox(IEnumerable<Polygon> polygons)
{
    double minX = double.MaxValue;
    double minY = double.MaxValue;
    double maxX = double.MinValue;
    double maxY = double.MinValue;

    foreach (Polygon polygon in polygons)
    {
        foreach (Point point in polygon.Points)
        {
            minX = Math.Min(minX, point.X);
            minY = Math.Min(minY, point.Y);
            maxX = Math.Max(maxX, point.X);
            maxY = Math.Max(maxY, point.Y);
        }
    }

    return new Rect(minX, minY, maxX - minX, maxY - minY);
}
相关推荐
玉面小君7 小时前
从 WPF 到 Avalonia 的迁移系列实战篇6:Trigger、MultiTrigger、DataTrigger 的迁移
wpf·avalonia
招风的黑耳1 天前
Java生态圈核心组件深度解析:Spring技术栈与分布式系统实战
java·spring·wpf
lfw20191 天前
WPF 数据绑定模式详解(TwoWay、OneWay、OneTime、OneWayToSource、Default)
wpf
Magnum Lehar1 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
FuckPatience2 天前
WPF Telerik.Windows.Controls.Data.PropertyGrid 自定义属性编辑器
wpf
almighty272 天前
C#WPF控制USB摄像头参数:曝光、白平衡等高级设置完全指南
开发语言·c#·wpf·usb相机·参数设置
军训猫猫头3 天前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
我要打打代码3 天前
在WPF项目中使用阿里图标库iconfont
wpf
拾忆,想起4 天前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
weixin_464078074 天前
wpf依赖注入驱动的 MVVM实现(含免费源代码demo)
wpf