使用GDI繪製驗證碼

效果圖:



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 使用GDI繪製驗證碼 : Form
    {
        public 使用GDI繪製驗證碼()
        {
            InitializeComponent();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Random rd = new Random();
            string str = null;
            for (int i = 0; i < 5; i++)
            {
                str += rd.Next(0,9);
            }
            //創建GDI對象
            Bitmap bmp = new Bitmap(150,40);
            Graphics g = Graphics.FromImage(bmp);
            //隨機生成的五個數(以及他們的顏色,字體都是隨機的
            for (int i = 0; i < 5; i++)
            {
                Point p = new Point(i*20,0);
                string[] fonts = {"微軟雅黑","宋體","黑體","隸書","仿宋" };
                Color[] colors = { Color.Red,Color.Green,Color.Blue,Color.Yellow,Color.Black};
                g.DrawString(str[i].ToString(), new Font(fonts[rd.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[rd.Next(0, 5)]), p);


            }
            //隨機生成的線條
            for (int i = 0; i < 20; i++)
            {
                Point p1 = new Point(rd.Next(0,bmp.Width),rd.Next(0,bmp.Height));
                Point p2 = new Point(rd.Next(0, bmp.Width), rd.Next(0, bmp.Height));
                g.DrawLine(new Pen(Brushes.Green),p1,p2);
            }
            //隨機生成的點
            for (int i = 0; i < 500; i++)
            {
                Point p = new Point(rd.Next(0,bmp.Width),rd.Next(0,bmp.Height));
                bmp.SetPixel(p.X,p.Y,Color.Black);
            }

            //將圖片鑲嵌到PictureBox
            pictureBox1.Image = bmp;
        }
    }
}


發佈了25 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章