public class BitmapRegion{//创建支持位图区域的控件(目前有button,form,imagebutton)public static void CreateControlRegion(Control control, Bitmap bitmap){//判断控件是否存在if (control == null )//|| bitmap == nullreturn;//控件大小设置为位图大小control.Width = bitmap.Width;control.Height = bitmap.Height;// 档控件为form时if (control is System.Windows.Forms.Form){//强制转化为formForm form = (Form)control;//当FORM的边界FormBorderStyle不为NONE时,应将FORM的大小设置成比位图大小稍大一点form.Width += 15;form.Height += 35;//设置form为没有边界form.FormBorderStyle = FormBorderStyle.None;//将位图设置为控件背景图form.BackgroundImage = bitmap;//计算位图中不透明的部分GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);//应用新的区域form.Region = new Region(graphicsPath);}//当控件是panel时else if (control is System.Windows.Forms.Panel){//强制转化为panelPanel form = control as Panel;//当FORM的边界FormBorderStyle不为NONE时,应将FORM的大小设置成比位图大小稍大一点//form.Width += 15;//form.Height += 35;//form.Width += 15;//form.Height += 35;// 设置panel为没有边界form.BorderStyle = BorderStyle.None;//将位图设置为控件背景图form.BackgroundImage = bitmap;//计算位图中不透明的部分GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);//应用新的区域form.Region = new Region(graphicsPath);}//当控件是button时else if (control is System.Windows.Forms.Button){// 强制转化为buttonButton button = (Button)control;// 不显示button文字button.Text = "";// 改变cursor的stylebutton.Cursor = Cursors.Hand;// 设置button的背景图片button.BackgroundImage = bitmap;// 计算图中不透明部分GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);// 应用新的区域button.Region = new Region(graphicsPath);}//当控件是imagebutton时else if (control is M3Host.view.utils.ImageButton){M3Host.view.utils.ImageButton button = control as M3Host.view.utils.ImageButton;// 不显示文字button.Text = "";// 改变模式和设置正常状态下的图片为空button.Cursor = Cursors.Hand;button.NormalImage = null;// 设置位图为背景图片button.BackgroundImage = bitmap;// 计算图中不透明部分GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);// 应用新的区域button.Region = new Region(graphicsPath);}}// 计算位图中不透明部分private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap){// 创建graphicsPathGraphicsPath graphicsPath = new GraphicsPath();// 取得左上角的第一个点作为透明点Color colorTransparent = bitmap.GetPixel(0, 0);// 第一个找到的点int colOpaquePixel = 0;// 遍历所有Y方向的点for (int row = 0; row < bitmap.Height; row++){// 重设colOpaquePixel = 0;// 遍历X方向的所有点for (int col = 0; col < bitmap.Width; col++){// 如果不是透明点,则继续遍历if (bitmap.GetPixel(col, row) != colorTransparent){// 记录当前点colOpaquePixel = col;// 新建变量记录当前点int colNext = col;// 从找到的不透明点开始,继续寻找不透明点,一直到找到或则达到图片宽度for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)if (bitmap.GetPixel(colNext, row) == colorTransparent)break;// 将不透明点加到graphics pathgraphicsPath.AddRectangle(new Rectangle(colOpaquePixel,row, colNext - colOpaquePixel, 1));//覆盖前一个点col = colNext;}}}return graphicsPath;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!