Reputation:
I want to draw a line between 2 points on a chart but I cannot use ChartStyle.Line so I tried to use Graphics.DrawLine.
My problem is that I cant draw on top of the chart. How can I solve this?
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);
EDIT:
FUNCTION THAT updates the value of the old and new points:
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);
}
STILL NOT WORKING
Upvotes: 2
Views: 1084
Reputation: 54433
You can use this function to convert DataPoints
to drawing 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);
}
If you have set the two DataPoints
(!!) pontoantigo
and pontoatual
you can write the PrePaint
event:
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));
}
Here is the result of combining this little post and setting the two DataPoints
like this:
DataPoint pontoantigo = chart1.Series[0].Points.First();
DataPoint pontoatual = chart1.Series[0].Points.Last();
Upvotes: 1