You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OxyPlot:如何获取PolygonAnnotation的文本位置或指定数据点?

解决OxyPlot中PolygonAnnotation文本位置获取与ArrowAnnotation连接问题

首先得明确:OxyPlot的PolygonAnnotation如果没有手动设置TextPosition,它的默认值就是{NaN, NaN}——哪怕你设置了文本的对齐方式为中心,控件也不会自动帮你计算并填充这个属性,得我们自己来处理。

下面给你两种可行的方案:

方案1:手动计算并设置PolygonAnnotation的TextPosition

你可以先计算多边形的边界框中心或者几何中心,把这个值赋值给TextPosition,之后就可以直接用这个属性作为箭头的起点/终点了。

示例代码(C#)

// 假设你有两个多边形注释
var polygon1 = new PolygonAnnotation
{
    Points = new List<DataPoint> { new(1,1), new(3,1), new(2,3) },
    Text = "多边形1",
    TextHorizontalAlignment = HorizontalAlignment.Center,
    TextVerticalAlignment = VerticalAlignment.Middle
};

var polygon2 = new PolygonAnnotation
{
    Points = new List<DataPoint> { new(5,2), new(7,2), new(6,4) },
    Text = "多边形2",
    TextHorizontalAlignment = HorizontalAlignment.Center,
    TextVerticalAlignment = VerticalAlignment.Middle
};

// 计算多边形1的边界框中心
var bounds1 = polygon1.GetBounds();
var center1 = new DataPoint(
    (bounds1.Left + bounds1.Right) / 2,
    (bounds1.Top + bounds1.Bottom) / 2
);
polygon1.TextPosition = center1;

// 计算多边形2的边界框中心
var bounds2 = polygon2.GetBounds();
var center2 = new DataPoint(
    (bounds2.Left + bounds2.Right) / 2,
    (bounds2.Top + bounds2.Bottom) / 2
);
polygon2.TextPosition = center2;

// 创建箭头注释连接两个中心
var arrow = new ArrowAnnotation
{
    StartPoint = center1,
    EndPoint = center2,
    Color = OxyColors.Red,
    StrokeThickness = 2
};

// 添加到PlotModel
plotModel.Annotations.Add(polygon1);
plotModel.Annotations.Add(polygon2);
plotModel.Annotations.Add(arrow);

方案2:直接计算中心作为箭头的起点/终点(无需依赖TextPosition)

如果你不想修改TextPosition,也可以直接把计算出来的中心坐标直接传给ArrowAnnotation的StartPoint和EndPoint,效果是一样的。

补充说明

  • 边界框中心:是多边形外接矩形的中心,适合大多数对齐场景;
  • 几何中心:是所有顶点坐标的平均值,计算方式是(平均X, 平均Y),如果多边形是不规则形状,这个中心可能和视觉中心有偏差,你可以根据需求选择。

比如计算几何中心的代码:

var avgX = polygon1.Points.Average(p => p.X);
var avgY = polygon1.Points.Average(p => p.Y);
var geometricCenter = new DataPoint(avgX, avgY);

这样处理后,就能精准地用箭头连接两个多边形的文本位置(或者说视觉中心)了。

内容的提问来源于stack exchange,提问作者Kunibert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:17:13