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);
}
相关推荐
诸葛务农1 天前
人形机器人——电子皮肤技术路线:光学式电子皮肤及MIT基于光导纤维的分布式触觉传感电子皮肤
分布式·机器人·wpf
界面开发小八哥2 天前
界面控件DevExpress WPF中文教程:Data Grid - 绑定数据
ui·.net·wpf·界面控件·devexpress·ui开发
界面开发小八哥2 天前
图表组件SciChart WPF再升级:v8.9带来油气井图、新交互与可视化增强
信息可视化·wpf·数据可视化·scichart
创可贴治愈心灵3 天前
WPF中UI线程频繁操作造成卡顿的处理
ui·c#·wpf
阿登林4 天前
初步学习WPF-Prism
学习·wpf
△曉風殘月〆4 天前
WPF MVVM进阶系列教程(三、使用依赖注入)
wpf·mvvm
此wei浩亦4 天前
WPF中使用 using prism.region 报错
c#·wpf·prism
dotent·5 天前
一个 WPF 文档和工具窗口布局容器
wpf
c#上位机5 天前
wpf之ComboBox
wpf
lindexi5 天前
WPF 引用 ASP.NET Core 的 AOT 版本
wpf·asp.netcore