Bla*_*lin 0 c# forms charts linechart winforms
I am using WinForms to create a line chart. I have two related questions:
How can I draw a vertical line on the chart?
I have tried to draw a vertical line between two points at (0,0) and (0,5) using:
chart1.Series["Pakistan"].Points.AddXY(0, 0);
chart1.Series["Pakistan"].Points.AddXY(0, 5);
Run Code Online (Sandbox Code Playgroud)
However, I get an askew line from (0,0) to (1,5).
How can I label this line with a string on the X axis?
您可以使用 aStripLine在 x 轴上显示一条垂直线:
StripLine stripLine = new StripLine();
stripLine.Interval = 0; // only show 1 line
stripLine.Offset = 0; // start it at x=0
stripLine.StripWidth = 1; // the width is 1
// set colors, etc
chart1.ChartAreas["Default"].AxisX.StripLines.Add(stripLine);
Run Code Online (Sandbox Code Playgroud)
您还可以创建第二系列 type RangeColumn,它在每个 x 值处接收 2 个 y 值,以创建垂直线:
Series lineSeries = chart1.Series.Add("line");
lineSeries.ChartType = RangeColumn;
lineSeries.Points.AddXY(0, new []{0, 1});
// Set line widths, colors, etc
Run Code Online (Sandbox Code Playgroud)
最后,您可以使用`Graphics 对象处理绘制线条的PostPaint事件Chart:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
if(sender is ChartArea)
{
ChartArea area = (ChartArea)sender;
if(area.Name == "Default")
{
// Get Graphics object from chart
Graphics graph = e.ChartGraphics.Graphics;
// Convert X and Y values to screen position
float pixelYMax = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.Y,1);
float pixelXMax = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.X,0);
float pixelYMin = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.Y,0);
float pixelXMin = (float)e.ChartGraphics.GetPositionFromAxis("Default",AxisName.X,0);
PointF point1 = PointF.Empty;
PointF point2 = PointF.Empty;
// Set Maximum and minimum points
point1.X = pixelXMax;
point1.Y = pixelYMax;
point2.X = pixelXMin;
point2.Y = pixelYMin;
// Convert relative coordinates to absolute coordinates.
point1 = e.ChartGraphics.GetAbsolutePoint(point1);
point2 = e.ChartGraphics.GetAbsolutePoint(point2);
// Draw connection line
graph.DrawLine(new Pen(Color.Yellow,3), point1,point2);
}
}
}
Run Code Online (Sandbox Code Playgroud)
处理PostPaint可能是最好的选择,它将让您最好地控制您的线路及其外观。
| 归档时间: |
|
| 查看次数: |
5801 次 |
| 最近记录: |