using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace TestBackGround
{
class ShowFrom
{
public ShowFrom()
{ }
//创建支持位图区域的控件
public static void CreateControlRegion(Control control, Bitmap bitmap)
{
//设置控件大小为位图大小
control.Width = bitmap.Width;
//设置窗体的宽度
control.Height = bitmap.Height;
//设置窗体的高度
//当控件为form时
if (control is System.Windows.Forms.Form)
{
//强制转换为form
Form form = (Form)control;
//当Form的边界FormBorderStyle不为None时,应将Form的大小设置成比位图大小稍大一点
form.Width = control.Width;
form.Height = control.Height;
//将Form的边界FormBorderStyle设置为不应用任何样式
form.FormBorderStyle = FormBorderStyle.None;
//将位图设为窗体背景
form.BackgroundImage = bitmap;
//计算位图中不隐藏部分的边界
GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
//应用到新的区域
form.Region = new Region(graphicsPath);
}
}
private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
{
//创建GraphicsPath对象
GraphicsPath graphicsPath = new GraphicsPath();
//得到左上角颜色
Color colorTransparent = bitmap.GetPixel(0 , 0);
//找到第一个坐标x
int colOpaquePixel = 0;
//偏历所有行(Y方向)
for (int row = 0; row < bitmap.Height; row++)
{
//重新指定colOpaquePixel的值
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;
//将不透明点加到GraphicsPath的AddRectangle()方法里
graphicsPath.AddRectangle(new Rectangle(colOpaquePixel , row , colNext - colOpaquePixel , 1));
col = colNext;
}
}
}
return graphicsPath;
}
}
}
在窗体加载时,让它去调用;
ShowFrom ShowFrom= new ShowFrom();
ShowFrom.CreateControlRegion(this, new Bitmap(@"图片地址"));