我有不同长度的图例文本,需要将图例项与图例左侧对齐以获得一致的布局。
| My Legend |
| X what I have now |
| X what I have now long | --> causes irregular layout
| X what I need |
| X what I need long | --> nice, regular layout
一定是显而易见的东西,但已经研究了好几个小时,而且似乎离工作示例还差得远。预先感谢您的帮助!
编辑:
我正在尝试制作一个饼图,因此有多个系列,每个系列都需要系列符号和适当的系列数据点文本,就像默认图例布局中的情况一样。我的图例创建方法:
public Legend CreateLegend()
{
var legend = new Legend();
legend.Enabled = true;
legend.Font = new Font("Arial", 11F);
legend.ForeColor = Color.FromArgb(102, 102, 102);
legend.InsideChartArea = "Result Chart";
legend.Position = new ElementPosition(50, 20, 50, height);
legend.LegendStyle = LegendStyle.Column;
return legend;
}
以及我的系列创建方法(目前将图例作为我的实验/想法的参数,用于此处的解决方案):
public Series CreateSeries(List<ChartDivision> series, Legend legend)
{
var seriesDetail = new Series();
seriesDetail.Name = "Result Chart";
seriesDetail.IsValueShownAsLabel = false;
seriesDetail.ChartType = SeriesChartType.Pie;
seriesDetail.BorderWidth = 2;
foreach(var datapoint in series)
{
var p = seriesDetail.Points.Add(datapoint.Logged);
p.LegendText = datapoint.Name;
}
seriesDetail.ChartArea = "Result Chart";
return seriesDetail;
}
最佳答案
这里谈到 System.Windows.Forms.DataVisualization.Charting.Chart
。这实际上是默认行为。
但是你可以覆盖它:
在设计器中选择图表,单击 Legends-property。在适当的图例中,编辑 CellColumns-Property。
默认情况下为空。您可以添加两列并将第一列设置为“ColumnType=SeriesSymbol
”以获取自定义列的默认值。然后,在第二列中,对齐属性(默认情况下在 MiddleCenter 上)应该是您要查找的内容。
这是我的测试程序:http://pastebin.com/ZTwMhsXB 在窗体中添加一个图表控件和两个按钮并运行它。但是,我无法重现您的问题。
请注意,我做了更多布线。您能否确认您在某处有这些行:
chart1.Legends.Add(leg);
// and
legend.Name = // whatever
seriesDetail.Legend = legend.Name;
否则可能您看到的不是您创建的图例,而是默认图例。如果不将图例添加到图表区,它是不可见的。
好的,现在我们到了文本在其列中左对齐的地步,列总是在图例区域内居中。请参阅此 SO 线程以获取解决方案:How to control winform mschart legend text alignment c#?
像这样编辑代码:
legend.LegendStyle = LegendStyle.Column;
legend.CellColumns.Add(new LegendCellColumn() {
ColumnType = LegendCellColumnType.SeriesSymbol,
MinimumWidth = 250,
MaximumWidth = 250
});
legend.CellColumns.Add(new LegendCellColumn()
{
ColumnType = LegendCellColumnType.Text,
Alignment = ContentAlignment.MiddleLeft,
MinimumWidth = 1500,
MaximumWidth = 1500
});
请注意,数字 250 和 1500 是字体大小的百分比,因此 1500 表示字体高度的 15 倍。 我相应地更新了 pastebin ( http://pastebin.com/GGCZGWF9 ),这是我的示例程序的屏幕截图:
关于c# - 如何在 Microsoft .net 图表中将图例内容左对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059292/