如何配置HorizontalLineAnnotation使其不超出图表框架边界
问题:HorizontalLineAnnotation 水平注释线超出图表坐标轴边界
开发过程中编写了为图表添加2条水平注释线(HorizontalLineAnnotation)的代码,具体实现如下:
public void populate() { HorizontalLineAnnotation hl = new HorizontalLineAnnotation(); hl.AllowMoving = false; hl.IsInfinitive = true; hl.LineColor = System.Drawing.Color.Red; hl.AnchorY = Convert.ToDouble(USLText.Text); hl.AxisX = DataChart.ChartAreas[0].AxisX; hl.AxisY = DataChart.ChartAreas[0].AxisY; DataChart.Annotations.Add(hl); HorizontalLineAnnotation hllsl = new HorizontalLineAnnotation(); hllsl.AllowMoving = false; hllsl.IsInfinitive = true; hllsl.LineColor = System.Drawing.Color.Blue; hllsl.AnchorY = Convert.ToDouble(LSLText.Text); hllsl.AxisX = DataChart.ChartAreas[0].AxisX; hllsl.AxisY = DataChart.ChartAreas[0].AxisY; DataChart.Annotations.Add(hllsl); // 其余业务逻辑与本问题无关,未附上 }
代码运行无报错,但实际渲染时注释线超出了图表坐标轴的边界范围,延伸到了整个窗口两端,效果如下:
需要调整配置修复注释线超出图表框架的问题。
原因分析
出现这个问题是因为没有给HorizontalLineAnnotation指定裁剪所属的图表区域,当IsInfinitive属性设为true时,注释线默认会在整个图表控件的宽度范围内绘制,不会自动被坐标轴边界裁剪。
修复方案
给每一条水平注释线设置ClipToChartArea属性,属性值为注释线所属图表区域的Name属性值即可,不需要修改IsInfinitive的配置,就能实现注释线刚好横跨整个绘图区域、不超出坐标轴边界的效果。
修正后的核心代码如下:
public void populate() { // 先获取目标图表区域实例,简化重复引用 var targetChartArea = DataChart.ChartAreas[0]; HorizontalLineAnnotation hl = new HorizontalLineAnnotation(); hl.AllowMoving = false; hl.IsInfinitive = true; hl.LineColor = System.Drawing.Color.Red; hl.AnchorY = Convert.ToDouble(USLText.Text); hl.AxisX = targetChartArea.AxisX; hl.AxisY = targetChartArea.AxisY; // 指定注释线裁剪到对应图表区域,避免超出边界 hl.ClipToChartArea = targetChartArea.Name; DataChart.Annotations.Add(hl); HorizontalLineAnnotation hllsl = new HorizontalLineAnnotation(); hllsl.AllowMoving = false; hllsl.IsInfinitive = true; hllsl.LineColor = System.Drawing.Color.Blue; hllsl.AnchorY = Convert.ToDouble(LSLText.Text); hllsl.AxisX = targetChartArea.AxisX; hllsl.AxisY = targetChartArea.AxisY; // 指定注释线裁剪到对应图表区域,避免超出边界 hllsl.ClipToChartArea = targetChartArea.Name; DataChart.Annotations.Add(hllsl); }
配置注意事项
- 如果图表包含多个ChartArea,要确保
ClipToChartArea填写的是注释线所属区域的正确Name,不要错配 - 该属性建议在将Annotation添加到
Annotations集合之前设置,避免首次渲染异常 - 不需要手动设置注释线的起始/结束X坐标,
IsInfinitive=true配合裁剪属性会自动适配X轴的实际显示范围
内容的提问来源于stack exchange,提问作者TheLostChild
相关产品推荐
相关产品推荐

