Asp.Net-GDI+画图示例
1,Demo1-矩形,椭圆,多边形画法
1) 首先我们创建一个网站,我们需要添加如下命名空间:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Drawing2D:包含了GDI+的新增类,提供高级的二维和矢量图形功能。
其中Graphics类是GDI+核心。
2) 我们在页面的Page_Load方法中添加如下代码:
//定义画笔
Pen MyPen1 = new Pen(Color.Black,5);
Pen MyPen2 = new Pen(Color.Black, 5);
Pen MyPen3 = new Pen(Color.Black, 5);
Pen MyPen4 = new Pen(Color.Black, 5);
Pen MyPen5 = new Pen(Color.Blue, 10);
Pen MyPen6 = new Pen(Color.Blue, 10);
Pen MyPen7 = new Pen(Color.Blue, 10);
//创建画布
Bitmap MyMap = new Bitmap(710,510);//创建了一个宽710,高150画布
Graphics MyG = Graphics.FromImage(MyMap);
//连接画笔
MyG.Clear(Color.White);
MyG.DrawLine(MyPen1,10,20,150,20);
MyG.DrawLine(MyPen2, 150, 20, 150, 100);
MyG.DrawLine(MyPen3, 150, 100, 10, 100);
MyG.DrawLine(MyPen4, 10, 100, 10, 20);
MyG.DrawLine(MyPen5, 50, 20, 48, 100);
MyG.DrawLine(MyPen6, 100, 20, 102, 100);
MyG.DrawLine(MyPen7, 50, 60, 100, 60);
//椭圆
Pen MyPen8 = new Pen(Color.Black,2);
MyG.DrawEllipse(MyPen8,250,20,250,120);//参数包含:使用的画笔,椭圆的起始坐标,宽,高
MyG.DrawEllipse(MyPen8, 275, 20, 200, 120);
MyG.DrawEllipse(MyPen8, 350, 20, 50, 120);
//创建多边形的点
Point p0 = new Point(600,10);
Point p1 = new Point(620, 60);
Point p2 = new Point(600, 110);
Point p3 = new Point(580, 60);
Point[] MyPoints = { p0, p1, p2, p3 };
//创建多边形
Pen MyPen9 = new Pen(Color.Black, 2);
MyG.DrawPolygon(MyPen9,MyPoints);//将MyPoints数组中每个孤立点连接成一个封闭的图形。
//把图像输出到HTTP响应流,从而显示在页面中
MyMap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);
MyMap.Dispose();
MyG.Dispose();
运行结果如图:
2)Demo2-进行图像的简单处理
1)添加如下命名空间:
using System.Drawing;
using System.Drawing.Drawing2D;
2) 我们在页面的Page_Load方法中添加如下代码:
Bitmap MyMap = new Bitmap(1024,768);
Graphics MyG = Graphics.FromImage(MyMap);
MyG.Clear(Color.White);
//创建图片路径
System.Drawing.Image img;
img = System.Drawing.Image.FromFile("F:\\A3.jpg");
//创建区域
Point point1=new Point(0,0);
Rectangle rct=new Rectangle(0,0,410,307);
//加载图片
MyG.DrawImage(img,point1);
//加载缩略图
MyG.DrawImage(img,rct);
//加载文字
MyG.DrawString("缩略图",new Font("宋体",18),Brushes.Red,new Point(320,20));
MyG.DrawString("原图",new Font("宋体",18),Brushes.Red,new Point(420,20));
//输出显示
MyMap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);
MyMap.Dispose();
MyG.Dispose();
运行结果如图: