简单来说就是画图的
先小试牛刀画个小图形
在点击事件里写下几行画正方形:
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Brushes.Black);
Rectangle rec = new Rectangle(50,50,80,80);
g.DrawRectangle(pen,rec);
在点击事件里写下几行画扇形:
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Brushes.Red);
Rectangle rec = new Rectangle(300, 150, 180, 180);
g.DrawPie(pen, rec, 160, 60);
分割线
简单图形练手已经结束,让我们开始
准备材料
1.一个pictureBox放验证码
先展示结果:
结果展示 |
---|
第一张图片 |
第二图,每次都不一样 |
先解释一下步骤
g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 15, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p);
画图,提前写好字体,颜色画的时候随机调用那么开始看源码:
private void pictureBox1_Click(object sender, EventArgs e)
{
Random r = new Random();
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(120, 25);
//FromImage(bmp)里边要一个image 但是Bitmap是继承与image的所以可行(里氏转换)
Graphics g = Graphics.FromImage(bmp);
for (int i = 0; i < 5; i++)
{
Point p = new Point(i * 20, 0);
string[] fonts = { "微軟雅黑", "宋體", "黑體", "隸書", "仿宋" };
Color[] colors = { Color.Blue, Color.Red, Color.Yellow, Color.Salmon, Color.Green };
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(r.Next(0, bmp.Width)), r.Next(0, bmp.Height));
Point p2 = new Point(r.Next(r.Next(0, bmp.Width)), r.Next(0, bmp.Height));
g.DrawLine(new Pen(Brushes.Green), p1, p2);
}
//加点像素颗粒继续让你看不清
for (int i = 0; i < 200; i++)
{
Point p = new Point(r.Next(r.Next(0, bmp.Width)), r.Next(0, bmp.Height));
bmp.SetPixel(p.X, p.Y, Color.Black);
}
//将图片镶嵌到PictBox里边
pictureBox1.Image = bmp;
}