首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。