试图绘制一个函数

时间:2015-04-01 01:50:21

标签: c#

我试图在c#中绘制图形,类似于enter image description here

到目前为止,我已经能够使用DrawLine绘制简单的线条,但这是非常有限的,因为,不仅我被迫提供起点和终点,我也只限于直线。

正如你所看到的那样

enter image description here

我在表达的最后一个trech(倒置抛物线)上有一条曲线

有关如何在bmp绘图中执行此操作的任何提示?

我使用以下

绘图
   using (Graphics g = Graphics.FromImage(bmp))
           { //g.DrawLine and others
}

2 个答案:

答案 0 :(得分:2)

您可以使用Graphics类DrawCurve中的类似函数。它将一个点数组作为参数,然后通过它们绘制。根据您想要曲线的精确程度,您可以获得起点,终点和转折点。

https://msdn.microsoft.com/en-us/library/7ak09y3z%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

答案 1 :(得分:0)

绘制函数的第一步是评估它并将其保存到Point数组:

        //Create a Point array to store the function's values
        Point[] functionValues = new Point[100];

        //Calculate the function for every Point in the Point array
        for (int x = 0; x < functionValues.Length; x++)
        {
            //Set the every point's X value to the current iteration of the loop. That means that we are evaluating the function in steps of 1
            functionValues[x].X = x;
            //Calculate the Y value of every point. In this exemple I am using the function x^2
            functionValues[x].Y = x * x;
        }

然后,当你绘制出函数时,像这样绘制它:

        //Iterate through every point in the array
        for (int i = 1; i < functionValues.Length; i++)
        {
            //Draw a line between every point and the one before it
            //Note that 'g' is your graphics object
            g.DrawLine(Pens.Black, functionValues[i-1], functionValues[i]);
        }

在绘图时,请在表单的Paint事件中执行此操作,并确保表单是双缓冲的:

    Point[] functionValues;

    public Form1()
    {
        InitializeComponent();
        this.DoubleBuffered = true;
        this.Paint += Form1_Paint; //Subscribe to the Paint Event

        //Create a Point array to store the function's values
        functionValues = new Point[100];

        //Calculate the function for every Point in the Point array
        for (int x = 0; x < functionValues.Length; x++)
        {
            //Set the every point's X value to the current iteration of the loop. That means that we are evaluating the function in steps of 1
            functionValues[x].X = x;
            //Calculate the Y value of every point. In this exemple I am using the function x^2
            functionValues[x].Y = x * x;
        }
    }

    void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        //Draw using 'g' or 'e.Graphics'.
        //For exemple:

        //Iterate through every point in the array
        for (int i = 1; i < functionValues.Length; i++)
        {
            //Draw a line between every point and the one before it
            g.DrawLine(Pens.Black, functionValues[i - 1], functionValues[i]);
        }

    }

并且,为了使表单更新并重新绘制自己,请调用表单的Invalidate方法:

this.Invalidate();