[英]C# - How to drawLine on top of the chart or another control
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. 我想在图表上的2个点之间绘制一条线,但我不能使用ChartStyle.Line,所以我尝试使用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: 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 还是行不通
You can use this function to convert DataPoints
to drawing Points
: 您可以使用此函数将
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);
}
If you have set the two DataPoints
(!!) pontoantigo
and pontoatual
you can write the PrePaint
event: 如果您设置了两个
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));
}
Here is the result of combining this little post and setting the two DataPoints
like this: 这是结合这个小帖子和设置两个
DataPoints
的结果,如下所示:
DataPoint pontoantigo = chart1.Series[0].Points.First();
DataPoint pontoatual = chart1.Series[0].Points.Last();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.