按钮控件在windows forms总是我们使用最多的控件之一了,可是你真的了解它吗?除了修改它的text属性以及该name的名字和增加事件处理的代码你还了解其他吗?
假如有这样一个需求,我们要做一个不规则的按钮,我们该具体如何实现呢?
好吧,别的先不多说了,我直接上实例代码。
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Borwer { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 返回指定图片中的非透明区域; /// </summary> /// <param name="img">位图</param> /// <param name="alpha">alpha 小于等于该值的为透明</param> /// <returns></returns> public static GraphicsPath GetNoneTransparentRegion(Bitmap img, byte alpha) { int height = img.Height; int width = img.Width; int xStart, xEnd; GraphicsPath grpPath = new GraphicsPath(); for (int y = 0; y < height; y++) { //逐行扫描 for (int x = 0; x < width; x++) { //略过连续透明的部分 while (x < width && img.GetPixel(x, y).A <= alpha) { x++; } //不透明部分 xStart = x; while (x < width && img.GetPixel(x, y).A > alpha) { x++; } xEnd = x; if (img.GetPixel(x - 1, y).A > alpha) { grpPath.AddRectangle(new Rectangle(xStart, y, xEnd - xStart, 1)); } } } return grpPath; } private void Form1_Load(object sender, EventArgs e) { pictbox.Visible = false; } private void button1_Paint(object sender, PaintEventArgs e) { Bitmap img = (Bitmap)pictbox.Image; GraphicsPath grapth = GetNoneTransparentRegion(img, 10); button1.Region = new Region(grapth); //要显示的图片设置为窗体背景; button1.BackgroundImage = pictbox.Image; button1.BackgroundImageLayout = ImageLayout.Zoom; //在修改窗体尺寸之前设置窗体为无边框样式; button1.Width = pictbox.Image.Width; button1.Height = pictbox.Image.Height; } private void button1_Click(object sender, System.EventArgs e) { MessageBox.Show("我是心状不规则按钮"); } private void button2_Click(object sender, System.EventArgs e) { MessageBox.Show("我是苹果不规则按钮"); } private void button2_Paint(object sender, PaintEventArgs e) { Bitmap img = (Bitmap)pictbox.Image; GraphicsPath grapth = GetNoneTransparentRegion(img, 10); button2.Region = new Region(grapth); //要显示的图片设置为窗体背景; button2.BackgroundImage = pictbox.Image; button2.BackgroundImageLayout = ImageLayout.Zoom; //在修改窗体尺寸之前设置窗体为无边框样式; button2.Width = pictbox.Image.Width; button2.Height = pictbox.Image.Height; } } }
运行结果:
上面的弹出框是点击心状按钮的回应,怎么样效果实现了吧,你可以选择一些更多的图片去玩玩看看,很爽的效果。
除非注明,木杉博客文章均为原创并采用BY-NC-SA协议进行授权原创文章,转载请注明: 转载自木杉博客
转载链接地址: C#基础温习(11):不规则按钮实现