首页 > 代码库 > C#画图——Graphics

C#画图——Graphics

  C#要实现简单的画图功能可以利用Graphics这个类,要使用Graphics必需using命名空间System.Drawing(此名明空间下都是关于图形的操作)。首先创建画布:

Bitmap bmp = new Bitmap(1000, 800);Graphics g = Graphics.FromImage(bmp);

  清除画布的背景色,并且指定颜色填充:

g.Clear(Color.White);

  开始画图:

//画矩形g.DrawRectangle(new Pen(Color.Red), new Rectangle(0, 0, 600, 400));//填充扇形g.FillPie(new SolidBrush(Color.Red), new Rectangle(100, 80, 200, 200), 0, 100);//在画布上写文字g.DrawString("A", new Font("Times New Roman", 16), new SolidBrush(Color.Black), 250, 210);

  下面给出完整代码:

技术分享
 1 public class GraphicsController : Controller 2 { 3         public ActionResult Index() 4         { 5             return View(); 6         } 7         [HttpGet] 8         public ActionResult CreateGraphics() 9         {10             Bitmap bmp = new Bitmap(1000, 800);11             //画布12             Graphics g = Graphics.FromImage(bmp);13             //清除画布背景色,并填充指定色14             g.Clear(Color.White);15             //画矩形16             g.DrawRectangle(new Pen(Color.Red), new Rectangle(0, 0, 600, 400));17             //画刷18             Brush bs = new SolidBrush(Color.Blue);19             //填充扇形20             g.FillPie(new SolidBrush(Color.Red), new Rectangle(100, 80, 200, 200), 0, 100);21             g.FillPie(bs, new Rectangle(100, 80, 200, 200), 100, 100);22             g.DrawPie(new Pen(bs), new Rectangle(100, 80, 200, 200), 200, 100);//画扇形23             g.FillPie(new SolidBrush(Color.HotPink), new Rectangle(100, 80, 200, 200), 300, 60);24             g.DrawString("A", new Font("Times New Roman", 16), new SolidBrush(Color.Black), 250, 210);25             //抗锯齿26             g.SmoothingMode = SmoothingMode.AntiAlias;27             MemoryStream ms = new MemoryStream();28             try29             {30                 bmp.Save(ms, ImageFormat.Gif);31                 return File(ms.ToArray(), @"image/Gif");32             }33             catch (Exception)34             {35                 return null;36             }37         }38 }
后台


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <img src="http://www.mamicode.com/Bitmap/CreateGraphics" width="1000" height="800" />
    </div>
</body>
</html>

   效果图(好像有点简陋(╯▽╰ )):

技术分享

  最后推荐一些前辈的总结(比我强太多了):

http://www.cnblogs.com/Jerry-Chou/archive/2012/03/20/2408064.html 

http://www.cnblogs.com/Jerry-Chou/archive/2012/03/21/2409590.html

http://www.cnblogs.com/beyond0309/archive/2008/04/15/1155003.html验证码也可以用这种方式生成

 

C#画图——Graphics