图表点和画线

时间:2014-12-19 08:46:17

标签: c# winforms gdi+

我想用3点创建图表然后画一条线。它将如下图所示 ![c#form chart] [1] 但我的编码几乎没有划线和没有点。请帮忙

public partial class Form5 : Form
{
    public Form5()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Point[] pts = { new Point(150, 12), new Point(130, 15), new Point(160, 18) };
        //int count = 0;

      //   pts[count] = new Point((int)NumericUpDown1.Value, (int)NumericUpDown2.Value);
        for (int i = 0; i < pts.Length; i++)
        {
            if (i != 0)
            {
                this.CreateGraphics().DrawLine(new Pen(Brushes.Black, 3), pts[i - 1], pts[1]);
            }
            else
            {
                this.CreateGraphics().DrawLine(new Pen(Brushes.Black, 3), pts[i], pts[1]);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

代码中的主要问题是硬编码pts[1]。您应该使用pts[i]代替。请记住 - C#中的数组索引从零开始。

此外,您不需要在每次迭代时创建图形。声明局部变量并将其移到循环外部。而不是在每次迭代时检查循环值,您可以在循环外移动第一个点绘图。然后,您将能够以相同的方式处理其他点:

var g = this.CreateGraphics();
var blackPen = new Pen(Brushes.Black, 3);

g.DrawLine(blackPen, pts[0], pts[0]);

for(i = 1; i < pts.Length; i++)
   g.DrawLine(blackPen, pts[i - 1], pts[i]);

注意:您已使用Linq标记标记了问题。当然,您可以使用Linq创建点对,并使用此对绘制线条:

var lines = pts.Zip(pts.Skip(1), (a,b) => new { a, b });

foreach(var line in lines)
    g.DrawLine(blackPen, line.a, line.b);

答案 1 :(得分:-1)

这是正确的代码:

// keep your data at class level:
// lists are more flexible than arrays:
List<Point> pts = new List<Point>();

 // all drawing in the paint event:
private void Form1_Paint(object sender, PaintEventArgs e)
{

    // put the pen creation in a using scope:
    using ( Pen Pen = new Pen(Color.Red, 3f) )
    {  
        // make the corners nicer:
        pen.MiterLimit = pen.Width / 2f;

        // drawing all lines in one call greatly improves quality.
        // we need at least two points:
        if (pts.Count > 1) e.Graphics.DrawLines( Pen, pts);
    }
}

// trigger the drawing when needed, eg when you have added more points:
private void button1_Click(object sender, EventArgs e)
{
    // maybe add more points..
    pts.AddRange( new Point[]  
                { new Point(150, 12), new Point(130, 15), new Point(160, 18) } );

    // trigger the paint event
    this.Invalidate();
}

考虑绘制到Panel!这样您就可以移动它并将所有控件独立放在Form ..

如果您认真考虑创建图表,请考虑使用工具箱的数据仓中的Chart控件!

它具有真实图表所需的一切,包括标记轴和多种显示风格。

要使用您的数据,只需几行:

using System.Windows.Forms.DataVisualization.Charting;
//..
private void button2_Click(object sender, EventArgs e)
{
    chart1.Legends.Clear();
    chart1.Series[0].ChartType = SeriesChartType.FastLine;
    chart1.Series[0].Color = Color.Red;
    chart1.Series[0].BorderWidth = 3;

    chart1.Series[0].Points.AddXY(130, 15);
    chart1.Series[0].Points.AddXY(150, 12);
    chart1.Series[0].Points.AddXY(160, 18);
}

请注意,我已经订购了这些点,但并非所有类型都需要。我使用Fastline并且你原来的订单也适用。它甚至可以显示具有相同X值的几个点..!诅咒它自动缩放..

另请注意,图表以自然方式显示Y值,即从下到上显示Y值,而GDI从上到下显示!

以下是显示图表的两种方式的屏幕截图:

enter image description here