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 try
29 {
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="/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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NT式驱动和WDM式驱动
- 下一篇: 梦想绽放获4亿元C轮融资