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);
}
相关推荐
快乐非自愿2 小时前
分布式锁—Redisson的同步器组件
分布式·wpf
△曉風殘月〆7 小时前
WPF预览并打印FlowDocument
wpf
wangnaisheng7 小时前
【WPF】Slider滑动方法(INotifyPropertyChanged、ValueChanged )响应速度对比分析
c#·wpf
蒋劲豪7 小时前
WPF有哪些使用率高的框架
c#·wpf
wangnaisheng7 小时前
【WPF】在System.Drawing.Rectangle中限制鼠标保持在Rectangle中移动?
c#·wpf
中土 不易1 天前
WPF中XAML的优点
wpf
无所谓จุ๊บ2 天前
使用AI整理知识点--WPF动画核心知识
c#·wpf
xcLeigh3 天前
WPF在特定领域的应用:打造一款专业的图像编辑工具
c#·wpf
吾与谁归in3 天前
WPF给ListBox中的每一项添加右键菜单功能
c#·wpf
千里码!3 天前
RocketMQ延迟消息深度解析:原理、实践与性能调优
wpf·rocketmq