一、前言
GDI+:Graphics Device Interface Plus也就是图形设备接口,它提供过了各种丰富的图形图像处理功能。用到的命名空间是System.Drawing,它提供了对GDI+基本图形功能的访问,主要是Graphics类、Bitmap类、Font类、Image类、Pen类、Color类等。
这里需要注意一点的是命名空间,不要和System.Windows.Media搞混淆了,因为这个命名空间下也有很多类似的类。
在WPF中,需要引用类库:
而在WinForm中是不需要的。
二、正题
绘图的第一步就是需要一个Graphics类型对象。
1、创建Graphics对象
创建Graphics对象主要有3种方式:
- 在窗体或者控件的Paint事件参数中直接引用Graphics对象
- 使用窗体或者控件的CreatGraphics方法
- 从继承自Image的任何对象创建Graphics对象(System.Drawing.Image)
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
}
public Form1()
{
InitializeComponent();
Graphics graphics = this.CreateGraphics();
}
上述两种方式在WinForm中是非常方便的。
在WPF中我们一般使用第三种方式,WPF的底层使用的DirectX,所以原生是没有System.Drawing命名空间的,需要我们引用类库。这里我们重点介绍第三种方式。
使用Graphics类的静态方法FromImage(Image image)创建Graphics对象
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
System.Drawing.Graphics graphics = Graphics.FromImage(image);
这种方式是使用Image对象创建一个Graphics对象,所以这种方式一般用于处理图片。
值得注意的一点是,graphics对象是一个非托管类型,所以使用的时候需要手动释放资源,或者使用using。
2、绘图
DrawString–绘制文本字符串
System.Drawing.Image image = System.Drawing.Image.FromFile(@"C:\Users\DELL\Desktop\A.png");
using (System.Drawing.Graphics graphics = Graphics.FromImage(image))
{
string waterMask = $"{DateTime.Now:G}";
Font font = new Font("yahei", 20);
SizeF size = graphics.MeasureString(waterMask, font);
graphics.DrawString(waterMask, font, System.Drawing.Brushes.Red, new PointF(image.Width - size.Width - 20, image.Height - size.Height - 20));
}
image.Save(@"C:\Users\DELL\Desktop\B.png");
上面是给图片添加水印的例子,其他它Draw方法暂不介绍。