一 什么是GDI+
GDI+(Graphics Device Interface)是一种绘图装置接口,可将应用程序和绘图硬件分隔,让我们能够编写与装置无关的应用程序。它可以让我们不需要注意特定显示装置的详细数据,便可在屏幕或打印机显示信息。我们可以呼叫GDI+类被所提供的方法,然后这些方法会适当地呼叫特定的装置驱动程序,而完成绘图。而且与.NET进行了更换的融合。
二 坐标系统
在GDI+中所采用的坐标系统,与平时人们较常用的坐标系统不同,主要差别在于,一般的二维坐标系,X轴与Y轴分别是往右往上递增(左图),而GDI+所采用的坐标系,X轴与Y轴则分别是往右往下递增(右图)。
1 绘制有一条直线
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 使用GDI绘制简单的图形
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//创建GDI对象
Graphics g = this.CreateGraphics();
//创建画笔对象
Pen pen = new Pen(Brushes.Black);
//创建两个点
Point p1 = new Point(30, 50);
Point p2 = new Point(250, 250);
g.DrawLine(pen, p1, p2);
}
int i = 0;
private void Form1_Paint(object sender, PaintEventArgs e)
{
i++;
label1.Text = i.ToString();
//创建GDI对象
Graphics g = this.CreateGraphics();
//创建画笔对象
Pen pen = new Pen(Brushes.Black);
//创建两个点
Point p1 = new Point(30, 50);
Point p2 = new Point(250, 250);
g.DrawLine(pen, p1, p2);
}
}
}
二 绘制验证码
利用picturebox进行随机生产数字、线条、颜色、字体等便可实现。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.IO;
namespace 绘制验证码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random r = new Random();
/// <summary>
/// 点击更换验证码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox1_Click(object sender, EventArgs e)
{
string str = null;
for (int i = 0; i<5;i++)
{
int rNumber = r.Next(0, 10);
str += rNumber;
}
//MessageBox.Show(str);
//创建GDI对象
Bitmap bmp = new Bitmap(200, 80);
Graphics g = Graphics.FromImage(bmp);
for(int i=0;i<5;i++)
{
Point p = new Point(i*20,0);
string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "放松" };
Color[] colors = { Color.Yellow, Color.Black, Color.Blue, Color.Red, Color.AliceBlue };
g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 15, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]),p);
}
for(int i=0;i<20;i++)
{
Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
g.DrawLine(new Pen(Brushes.Green), p1, p2);
}
for(int i=0;i<500;i++)
{
Point p = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));
bmp.SetPixel(p.X, p.Y, Color.Black);
}
//将图片镶嵌到pictureb中
pictureBox1.Image = bmp;
}
}
}