直接上代码,主要部分为设置操作graphics对象的Transform属性。using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace BarChart { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true); } // Draw a bar chart filling the form. private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; const int MIN_YEAR = 1990; const int MAX_YEAR = 2001; const int MIN_SALES = 0; const int MAX_SALES = 30000000; // Map the coordinates 1990 <= X <= 2001, 0 <= Y <= 30M // to the form//s client area, minus a 10 pixel margin. //此处第7,8个参数为坐标所以-10 MapRectangles(e.Graphics, MIN_YEAR, MAX_YEAR, MIN_SALES, MAX_SALES, 10, this.ClientSize.Width - 10, this.ClientSize.Height - 10, 10); // Make some data. Point[] sales_data = { new Point(1990, 4000000), new Point(1991, 3000000), new Point(1992, 5000000), new Point(1993, 10000000), new Point(1994, 9000000), new Point(1995, 14000000), new Point(1996, 19000000), new Point(1997, 18000000), new Point(1998, 22000000), new Point(1999, 27000000), new Point(2000, 30000000) }; // Draw the data. using (Pen thin_pen = new Pen(Color.Green, 0)) { // Draw the bars. foreach (Point pt in sales_data) { e.Graphics.FillRectangle(Brushes.PaleGreen, pt.X, 0, 1, pt.Y); e.Graphics.DrawRectangle(thin_pen, pt.X, 0, 1, pt.Y); } // Translate 1/2 year horizontally // so the points lie in the middle of each bar. e.Graphics.TranslateTransform(0.5f, 0f, MatrixOrder.Prepend); thin_pen.Color = Color.Red; e.Graphics.DrawLines(thin_pen, sales_data); } // Draw a box around it all. e.Graphics.ResetTransform(); //此处的第四个参数为宽度所以-20 e.Graphics.DrawRectangle(Pens.Blue, 10, 10, this.ClientSize.Width - 20, this.ClientSize.Height - 20); } // Transform the Graphics object so // world coordinates wxmin <= X <= wxmax, wymin <= Y <= wymax are mapped to // device coordinates dxmin <= X <= dxmax, dymin <= Y <= dymax. private void MapRectangles(Graphics gr, float wxmin, float wxmax, float wymin, float wymax, float dxmin, float dxmax, float dymin, float dymax) { // Make a world coordinate rectangle. RectangleF wrectf = new RectangleF(wxmin, wymin, wxmax - wxmin, wymax - wymin); // Make PointF objects representing the upper left, upper right, // and lower right corners of device coordinates. PointF[] dpts = { new PointF(dxmin, dymin),//左上角 new PointF(dxmax, dymin),//右上角 new PointF(dxmin, dymax)//左下角 }; try // Map the rectangle to the points. { gr.Transform = new Matrix(wrectf, dpts); } catch (System.ArgumentException) {MessageBox.Show("错误操作");} } } }
图片为:
原始代码源自:C# graphics programing,做了少量修改,加入了异常处理。