900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > C#Winform实现手写录入签名与保存为透明png图片

C#Winform实现手写录入签名与保存为透明png图片

时间:2020-01-16 06:30:14

相关推荐

C#Winform实现手写录入签名与保存为透明png图片

C#Winform实现手写录入签名与保存为透明png图片

原理效果图实现代码

原理

在Winform窗体程序中实现鼠标手写输入其实就是画线,基本实现原理是放置一个PictureBox控件,订阅此控件的MouseMove和MouseDown事件,然后通过System.Drawing.Drawing2D.GraphicsPath在MouseMove事件中不断的画线。

效果图

实现代码

using System;using System.Collections.Generic;using ponentModel;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;#endregionpublic 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}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。