我想在图表上的2个点之间绘制一条线,但我不能使用ChartStyle.Line,所以我尝试使用Graphics.DrawLine。
我的问题是我无法在图表上绘图。我该如何解决这个问题?
PointF pontoantigo = new PointF();
if (chart1.Series[0].Points.Count > 0)
{
pontoantigo = new PointF((int)chart1.Series[0].Points[0].XValue, (int)chart1.Series[0].Points[0].YValues[0]);
}
chart1.Series[0].Points.Clear();
chart1.Series[0].Points.AddXY(posicao_atual_master.X, posicao_atual_master.Y);
PointF pontoatual = new PointF((int)chart1.Series[0].Points[0].XValue, (int)chart1.Series[0].Points[0].YValues[0]);
Pen p = new Pen(Color.Red);
Graphics g = chart1.CreateGraphics();
g.DrawLine(p, pontoantigo, pontoatual);
编辑:
更新旧点和新点值的功能:
pontoantigo = new PointF();
if (chart1.Series[0].Points.Count > 0)
{
pontoantigo = new PointF((int)chart1.Series[0].Points[0].XValue, (int)chart1.Series[0].Points[0].YValues[0]);
}
chart1.Series[0].Points.Clear();
chart1.Series[0].Points.AddXY(posicao_atual_master.X, posicao_atual_master.Y);
pontoatual = new PointF((int)chart1.Series[0].Points[0].XValue, (int)chart1.Series[0].Points[0].YValues[0]);
POSTPAINT:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
Pen p = new Pen(Color.Red);
Graphics g = e.ChartGraphics.Graphics;
g.DrawLine(p, pontoantigo, pontoatual);
}
仍然没有工作
答案 0 :(得分:0)
您可以使用此功能将DataPoints
转换为图纸Points
:
Point PointFromDataPoint(Chart chart, ChartArea ca, DataPoint pt)
{
Axis ax = chart2.ChartAreas[0].AxisX;
Axis ay = chart2.ChartAreas[0].AxisY;
int x = (int)ax.ValueToPixelPosition(pt.XValue);
int y = (int)ay.ValueToPixelPosition(pt.YValues[0]);
return new Point(x, y);
}
如果您设置了两个DataPoints
(!!)pontoantigo
和pontoatual
,则可以撰写PrePaint
事件:
private void chart1_PrePaint(object sender, ChartPaintEventArgs e)
{
using (Pen pen = new Pen(Color.Green, 2f))
e.ChartGraphics.Graphics.DrawLine(pen,
PointFromDataPoint(chart1, chart1.ChartAreas[0], pontoantigo),
PointFromDataPoint(chart1, chart1.ChartAreas[0], pontoatual));
}
以下是合并this little post并将DataPoints
设置为这样的结果:
DataPoint pontoantigo = chart1.Series[0].Points.First();
DataPoint pontoatual = chart1.Series[0].Points.Last();