C#Winform实现手写录入签名与保存为透明png图片
原理
在Winform窗体程序中实现鼠标手写输入其实就是画线,基本实现原理是放置一个PictureBox控件,订阅此控件的MouseMove和MouseDown事件,然后通过System.Drawing.Drawing2D.GraphicsPath在MouseMove事件中不断的画线。
效果图
实现代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication2
{public partial class Form1 : Form{#region 定义变量private System.Drawing.Drawing2D.GraphicsPath mousePath &#61; new System.Drawing.Drawing2D.GraphicsPath();private int myAlpha &#61; 100;private Color myUserColor &#61; new Color();private int myPenWidth &#61; 3;public Bitmap SavedBitmap;#endregionpublic Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){string url &#61; Cachet.CreatPublicSeal.CreatSeal("青岛弯弓信息技术有限公司", "数据服务部", "e:\\seal");this.pictureBox1.Image &#61; Image.FromFile(url);Console.WriteLine(url);}private void Form1_Load(object sender, EventArgs e){this.pictureBox1.BackColor &#61; Color.White; }#region 鼠标移动事件处理private void pictureBox1_MouseMove(object sender, MouseEventArgs e){if (e.Button &#61;&#61; System.Windows.Forms.MouseButtons.Left){try{mousePath.AddLine(e.X, e.Y, e.X, e.Y);}catch (Exception ex){MessageBox.Show(ex.Message);}}pictureBox1.Invalidate();}#endregion#region 鼠标按下事件处理private void pictureBox1_MouseDown(object sender, MouseEventArgs e){if (e.Button &#61;&#61; System.Windows.Forms.MouseButtons.Left){mousePath.StartFigure();}}#endregion#region 图片空间画图事件处理private void pictureBox1_Paint(object sender, PaintEventArgs e){try{myUserColor &#61; System.Drawing.Color.Blue;myAlpha &#61; 255;Pen CurrentPen &#61; new Pen(Color.FromArgb(myAlpha, myUserColor), myPenWidth);e.Graphics.DrawPath(CurrentPen, mousePath);}catch { }}#endregion#region 把图片中的内容保存为透明png图片private void btnSave_Click(object sender, EventArgs e){SavedBitmap &#61; new Bitmap(pictureBox1.Width, pictureBox1.Height);pictureBox1.DrawToBitmap(SavedBitmap, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));#region 保存为透明的png图片Bitmap bmp &#61; SavedBitmap;BitmapData data &#61; bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);int length &#61; data.Stride * data.Height;IntPtr ptr &#61; data.Scan0;byte[] buff &#61; new byte[length];Marshal.Copy(ptr, buff, 0, length);for (int i &#61; 3; i < length; i &#43;&#61; 4){if (buff[i - 1] >&#61; 230 && buff[i - 2] >&#61; 230 && buff[i - 3] >&#61; 230){buff[i] &#61; 0;}}Marshal.Copy(buff, 0, ptr, length);bmp.UnlockBits(data);bmp.Save("e:\\zhenglibing.png", ImageFormat.Png);#endregion}#endregion#region 清空图片的内容private void btnClear_Click(object sender, EventArgs e){pictureBox1.CreateGraphics().Clear(Color.White);mousePath.Reset();}#endregion}
}