2009-08-08 58 views
2

我試圖通過C#繪製一個簡單的條形圖,但我從未嘗試過使用圖形和繪圖命名空間。我想要生成一個「開始」和「結束」的圖形,然後重複一個圖像(顯示「長度」),但我不知道如何做到這一點。C#:繪製自己的條形圖

如果你能指向正確的方向和/或如果你有示例代碼來做到這一點,我會非常高興。

回答

-2

這有什麼錯用一個簡單的循環?

7

亞歷克斯,這是一個非常簡單的例子,讓你開始。要測試代碼,只需將面板控件添加到窗體併爲其創建一個繪製事件處理程序。 (雙擊設計器中的面板應該默認執行它。)然後用下面的代碼替換處理程序代碼。

該代碼在面板上繪製任意長度的五個小節,小節寬度和高度與面板寬度和高度有關。代碼是任意的,但是引入.Net繪圖功能是一種很好且簡單的方法。

void Panel1Paint(object sender, PaintEventArgs e) 
{ 
    Graphics g = e.Graphics; 
    int objCount = 5; 

    for (int n=0; n<objCount; n++) 
    { 
     g.FillRectangle(Brushes.AliceBlue, 0, n*(panel1.Height/objCount), 
         panel1.Width/(n+1), panel1.Height/objCount); 
     g.DrawRectangle(new Pen(Color.Black), 0, n*(panel1.Height/objCount), 
         panel1.Width/(n+1), panel1.Height/objCount); 
     g.DrawString(n.ToString(), new Font("Arial", 10f), Brushes.Black, 
        2, 2+n*(panel1.Height/objCount)); 
    } 
} 
1

基於保羅薩西克的答覆,我創建了一個有點不同簡單的條形圖。我希望這可以幫助其他人。

void DrawTheBar(int[] Values, Panel p) 
    {      
     //configuration of the bar chart 
     int barWidth = 20; //Width of the bar 
     int barSpace = 5; //Space between each bars. 
     int BCS = 5; //Background cell size 
     float fontSize = 8; 
     string fontFamily = "Arial";   

     Color bgColor = Color.White; 
     Brush fillColor = Brushes.CadetBlue; 
     Color borderColor = Color.Black; 
     Color bgCellColor = Color.Silver; 
     Brush textColor = Brushes.Black; 

     //do some magic here... 
     p.BackColor = bgColor; //set the bg color on panel 
     Graphics g = p.CreateGraphics(); 
     g.Clear(bgColor); //cleans up the previously draw pixels 
     int Xpos = barSpace; //initial position 
     int panelHeight = panel1.Height-1; //fix panel height for drawing border 

     //Drawing rectangles for background. 
     for(int c = 0; c < Convert.ToInt16(panel1.Width/BCS); c++) 
     { 
      for(int r = 0; r < Convert.ToInt16(panel1.Height/BCS); r++) 
      { 
       g.DrawRectangle(new Pen(bgCellColor), c * BCS, r * BCS, BCS, BCS); 
      } 
     } 

     //Drawing the bars 
     for(int i = 0; i < Values.Length; i++) 
     { 
      //Drawing a filled rectangle. X = Xpos; Y = ((panel Height - 1) - Actual value); Width = barWidth, Height = as value define it 
      g.FillRectangle(fillColor, Xpos, (panelHeight - Values[i]), barWidth, Values[i]); 
      //Draw a rectangle around the previously created bar. 
      g.DrawRectangle(new Pen(borderColor), Xpos, (panelHeight - Values[i]), barWidth, Values[i]); 
      //Draw values over each bar. 
      g.DrawString(Values[i].ToString(), new Font(fontFamily, fontSize), textColor, (Xpos + 2), (panelHeight - Values[i]) - (fontSize + barSpace)); 

      //calculate the next X point for the next bar. 
      Xpos += (barWidth + barSpace); 
     } 

     //here you will be happy with the results. :) 
    }