【问题标题】:Get Form.Left value of Point(X,Y) in ChartControl获取 ChartControl 中 Point(X,Y) 的 Form.Left 值
【发布时间】:2016-10-19 09:05:35
【问题描述】:

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

干杯

【问题讨论】:

  • 如果您希望在调整表单大小时更改它,您可以更改图表的锚点

标签: c# charts position converter datapoint


【解决方案1】:

假设您的意思是DataPoint 与XValue = 0 和YValue[0] = 0 的位置,您可以为此使用XAxis 函数ValueToPixelPosition;这是一个示例,假设您已将Label lbl 添加到图表的Controls 并将保持Label 位于第三个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 事件似乎也有效。

在其他时间使用它们,尤其是在图表完成布局之前,会产生错误或空值。

px、py 像素值是相对于图表的。要将它们转换为相对于 Form 的 Point,您可以使用常用的转换函数 PointToScreen 和 PointToClient。


更新:

如果你真的想要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;

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

【讨论】:

  • 嗨,这基本上是我要找的,但我不想将标签附加到数据点。我希望将标签附加到图表的左上角。并留在那里。图片:link欢呼
  • 嗨,我已经更新了答案以显示如何将标签粘贴到内部图表区域的左上角。
  • 完美答案 :D 这正是我想要的。
  • 如果您对答案感到满意,请考虑accepting it..!
【解决方案2】:

解决方案

这是我需要的代码。它在调整图表大小时使标签靠近左上角。同样,当 Y 轴移动时,标签会粘在上面。

感谢@TaW 提供所需的代码(见答案 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);

【讨论】:

  • 从答案的第二部分得到的效果相同,但不依赖于设置的最大值。
猜你喜欢
  • 2022-12-02
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
相关资源
最近更新 更多