C#:绘制自己的条形图

我试图通过C#绘制一个简单的条形图,但我从未尝试过使用Graphics和Drawing命名空间。 我想过生成一个“开始”和“结束”图形,然后以某种方式重复一个图像(显示“长度”),但我不知道如何做到这一点。

如果你能指出我正确的方向和/或你是否有示例代码来执行此操作,我会非常高兴。

我必须同意爱神。 有很多非常好的图形库可以完成你想要的。 我遇到的最好的:

  • Microsoft图表控件 – 甚至还有一个Visual Studio 插件和一个很好的教程 。
  • Flot – 这个是基于jQuery的,非常适合网络应用。
  • 谷歌图表 – 简单的API,甚至是ASP.Net控件

亚历克斯,这是一个非常简单的例子,可以帮助您入门。 要测试代码,只需在表单中添加一个面板控件,然后为其创建一个paint事件处理程序。 (双击设计器中的面板,默认情况下应该这样做。)然后用下面的代码替换处理程序代码。

代码在面板上绘制五个任意长度的条形,条形宽度和高度与面板宽度和高度相关。 代码是任意的,但是引入.Net绘图function的简单方法。

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

为什么不试试http://zedgraph.org/wiki/index.php?title=Main_Page 。 构建(和测试)自己的图形控件所需的时间太长

根据Paul Sasik的回复,我创建了一个不同的简单条形图。 我希望这可以帮助别人。

 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. :) } 

使用简单的循环有什么问题?