在ChartControl中获取Point(X,Y)的Form.Left值

时间:2016-10-19 09:05:35

标签: c# charts position converter datapoint

我需要图表控件中特定点的左值(或屏幕上的位置)。 基本上是0,0点,因为它在调整表格大小时会发生变化。

欢呼声

2 个答案:

答案 0 :(得分:0)

假设您的意思是DataPointXValue = 0YValue[0] = 0的位置,您可以使用XAxis函数ValueToPixelPosition。这是一个示例,假设您已向图表的Label lbl添加了Controls,并将Label保持在第3个DataPoint的位置:

private void chart1_Resize(object sender, EventArgs e)
{
    DataPoint dp = chart1.Series[0].Points[2];
    ChartArea ca = chart1.ChartAreas[0];
    Axis ax = ca.AxisX;
    Axis ay = ca.AxisY;

    int px = (int) ax.ValueToPixelPosition(dp.XValue);
    int py = (int) ay.ValueToPixelPosition(dp.YValues[0]);

    lbl.Location = new Point(px, py);
}

请注意,此函数以及其他转换函数(PixelPositionToValue)仅适用于Pre/PostPaint事件或鼠标事件。 Resize事件似乎也有效。

在其他时间使用它们,最明显的是在图表完成布局之前,将产生错误或空值。

enter image description here

px,py像素值相对于Chart。要将它们转换为相对于表单的Point,您可以使用常用的转换函数PointToScreenPointToClient

<强>更新

如果您确实想要ChartArea.InnerPlotPosition左上角的像素坐标,可以使用these two functions

RectangleF ChartAreaClientRectangle(Chart chart, ChartArea CA)
{
    RectangleF CAR = CA.Position.ToRectangleF();
    float pw = chart.ClientSize.Width / 100f;
    float ph = chart.ClientSize.Height / 100f;
    return new RectangleF(pw * CAR.X, ph * CAR.Y, pw * CAR.Width, ph * CAR.Height);
}

RectangleF InnerPlotPositionClientRectangle(Chart chart, ChartArea CA)
{
    RectangleF IPP = CA.InnerPlotPosition.ToRectangleF();
    RectangleF CArp = ChartAreaClientRectangle(chart, CA);

    float pw = CArp.Width / 100f;
    float ph = CArp.Height / 100f;

    return new RectangleF(CArp.X + pw * IPP.X, CArp.Y + ph * IPP.Y,
                            pw * IPP.Width, ph * IPP.Height);
}

可能在Resize这样的事件中使用它:

ChartArea ca = chart1.ChartAreas[0];
Rectangle ipr = Rectangle.Round(InnerPlotPositionClientRectangle(chart1, ca));
lbl.Location =  ipr.Location;

enter image description here

如果你现在想要,你可以轻松地将它偏移几个像素。

答案 1 :(得分:0)

SOLUTION

this was the Code I needed. It keeps the labels close to the upper left corner while resizeing the chart. Also when the Y Axis moves, the labels stick to it.

Thanks to @TaW for providing the needed Code (See answer 1)

            ChartArea ca = prodChart.ChartAreas[0];

            Axis ax = ca.AxisX;
            Axis ay = ca.AxisY;
            int px = (int)ax.ValueToPixelPosition(ax.Minimum + (ax.Maximum * 0.01));
            int py = (int)ay.ValueToPixelPosition(ay.Maximum - (ay.Maximum * 0.02));
            px = px - 5;
            qtyLabel.Location = new Point(px, py);
            sheetNameLabel.Location = new Point(px, py + 17);
            dateRangeLabel.Location = new Point(px, py + 34);