2015-04-01 131 views
0

我想畫在C#中的圖形,像enter image description here試圖繪製函數

到目前爲止,我已經能夠得出使用DrawLine簡單的線條,但是這是非常限制了自己的,因爲,不僅我被迫提供起點和終點,我也被限制爲直線。

正如你所看到的

enter image description here

我在表達的最後trech(一倒拋物線)的曲線

關於如何將BMP圖中執行此任何提示?

我一直在使用以下

using (Graphics g = Graphics.FromImage(bmp)) 
      { //g.DrawLine and others 
} 
+0

我是指你sinelaw的回答是:http://stackoverflow.com/questions/ 14371085/plot-a-line-y-2x-7-on-a-graph – renouve 2015-04-01 01:56:04

回答

2

您可以使用從Graphics類DrawCurve類似的功能繪圖。它將一系列點作爲參數,然後通過它們進行繪製。根據您想要曲線的準確度,您可以獲取起點,終點和轉折點。

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

+0

我會試試看,但是用這些函數創建一個點數組似乎是可能需要一些修補程序 – ng80092b 2015-04-01 02:02:51

+0

要添加到(正確)答案:還有一個過載讓你控制緊張;很有幫助! - 給定一個,我的和兩個Tc和Td值,在創建十幾個點時會出現問題? – TaW 2015-04-01 06:08:01

0

第一步,繪製函數將對其進行評估,並將其保存到一個點陣列:

 //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]); 
     } 

    } 

而且lastley,使形式更新和重新繪製自己,請致電形式的Invalidate方法:

this.Invalidate();