在C中制作统计图,可以使用`System.Drawing`命名空间中的类来绘制柱状图、折线图和扇形图。以下是一个简单的示例,展示如何使用C和WinForms绘制柱状图:
创建一个新的Windows窗体应用程序项目 。在窗体上添加一个PictureBox控件
,用于显示统计图。
编写代码来绘制统计图。
```csharp
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
public class ChartForm : Form
{
private PictureBox pictureBox;
public ChartForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.pictureBox = new PictureBox();
this.Controls.Add(this.pictureBox);
this.ClientSize = new System.Drawing.Size(800, 600);
this.Name = "ChartForm";
this.Text = "统计图";
this.Load += new System.EventHandler(this.ChartForm_Load);
}
private void ChartForm_Load(object sender, EventArgs e)
{
// 设置图片大小
int width = 800;
int height = 600;
// 创建一个Bitmap对象
Bitmap image = new Bitmap(width, height);
// 获取Graphics对象
Graphics g = Graphics.FromImage(image);
// 设置画笔和画刷
Pen mypen = new Pen(Color.Black, 1);
SolidBrush mybrush = new SolidBrush(Color.White);
Font font = new Font("Arial", 10, FontStyle.Bold);
// 绘制图框
g.FillRectangle(Brushes.WhiteSmoke, 0, 0, width, height);
// 绘制横向坐标线
g.DrawLine(mypen, 0, height / 2, width, height / 2);
// 绘制纵向坐标线
g.DrawLine(mypen, width / 2, 0, width / 2, height);
// 绘制横坐标值
g.DrawString("X轴", font, mybrush, 10, 20);
g.DrawString("Y轴", font, mybrush, width / 2 - 50, 20);
// 定义数组存储数据库中统计的数据
int[] data = { 10, 20, 30, 40, 50 };
// 绘制柱状图
int x = 20;
int y = height / 2 - 10;
for (int i = 0; i < data.Length; i++)
{
g.FillRectangle(mybrush, x, y - data[i], 50, data[i]);
g.DrawString(data[i].ToString(), font, mybrush, x + 60, y);
x += 50;
}
// 将图片显示在PictureBox控件中
pictureBox.Image = image;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ChartForm());
}
}
```
代码说明:
创建Bitmap对象:
用于存储绘制的图像。
获取Graphics对象:
用于在Bitmap对象上进行绘图操作。
设置画笔和画刷:
用于绘制不同的图形和文本。
绘制图框:
使用白色烟雾填充背景。
绘制坐标轴:
绘制横向和纵向坐标线,并在轴上标注单位。
绘制数据:
定义一个数组存储数据,并绘制柱状图,每个柱子的高度表示数据的大小。
显示图像:
将绘制的图像显示在PictureBox控件中。
通过上述步骤和代码,你可以在C中制作出经典的统计图。你可以根据需要修改数据和样式,以适应不同的统计需求。