C#_GDI+绘图(一)GDI+简介

一、前言

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方法暂不介绍。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值