原理
在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 = new System.Drawing.Drawing2D.GraphicsPath();
//画笔透明度
private int myAlpha = 100;
//画笔颜色对象
private Color myUserColor = new Color();
//画笔宽度
private int myPenWidth = 3;
//签名的图片对象
public Bitmap SavedBitmap;
#endregion
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string url = Cachet.CreatPublicSeal.CreatSeal("青岛弯弓信息技术有限公司", "数据服务部", "e:\\seal");
this.pictureBox1.Image = Image.FromFile(url);
Console.WriteLine(url);
}
private void Form1_Load(object sender, EventArgs e)
{
this.pictureBox1.BackColor = Color.White; //设置图片初始背景色为白色
}
#region 鼠标移动事件处理
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == 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 == System.Windows.Forms.MouseButtons.Left)
{
mousePath.StartFigure();
}
}
#endregion
#region 图片空间画图事件处理
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
try
{
myUserColor = System.Drawing.Color.Blue;
myAlpha = 255;
Pen CurrentPen = 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 = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(SavedBitmap, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
#region 保存为透明的png图片
Bitmap bmp = SavedBitmap;
BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
int length = data.Stride * data.Height;
IntPtr ptr = data.Scan0;
byte[] buff = new byte[length];
Marshal.Copy(ptr, buff, 0, length);
for (int i = 3; i < length; i += 4)
{
if (buff[i - 1] >= 230 && buff[i - 2] >= 230 && buff[i - 3] >= 230)
{
buff[i] = 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
}
}