问题描述
在一个Canvas中绘制了多个Polygon,由于坐标可能超出界面显示范围,需要将绘制的Polygon居中显示,并且缩放至界面大小,效果如下:
xaml代码
<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>
实现代码
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);
}
原文地址:https://blog.csdn.net/qq_29242649/article/details/134727158
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_26348.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。