日期:2013-02-12  浏览次数:20352 次

C#制作不规则窗口 ( 24bit Color 以上适用 )
時間: 2004/3/17
作者: Robert
參考: http://www.codeproject.com/csharp/bmprgnform.asp?target=region
電郵: zsc771120@yahoo.com.cn
關鍵字: Region Gif 不規則 窗口 視窗 GraphicsPath 按鈕 圖片 Form Button
目的: 幫助受 C# 不規則窗口困擾的人
介紹
這篇文章說明怎麼製作圖片按鈕和窗體. Region 技術不但能做不規則窗口, 也能做不規則控件外觀, 比
如說不規則按鈕.
程序介紹
說明: 我修改程序介紹中的注釋, 不修改程序列表的說明. 畢竟 E 文我們看起來沒有中文舒服.
1. 主函數說明
下面的程序用倆個主函數產生 位圖區域 (bitmap regionss ), 源代碼放在 BitmapRegion.cs中, 你可
以直接導入這個類別, 使用裡面的函數.
// Create and apply the given bitmap region on the supplied control
// 產生支持位圖區域 ( bitmap region ) 控件
public static void CreateControlRegion(Control control, Bitmap bitmap)
{
// 如果控件或者位圖不存在, 直接返回.
if(control == null || bitmap == null)
return;

// 根據位圖大小設置控件尺寸
control.Width = bitmap.Width;
control.Height = bitmap.Height;
// 處理 窗體 ( Form ) 類別
if(control is System.Windows.Forms.Form)
{
// 強制轉換 control object 到 Form object
Form form = (Form)control;
// 由於我們的Form邊界類型 ( Form.FormBorderStyle ) 不是 None,
// 所以我們的Form尺寸比位圖大一點
form.Width += 15;
form.Height += 35;

// 設定 Form 邊界類型是 None
form.FormBorderStyle = FormBorderStyle.None;
// 設定 Form 背景圖片
form.BackgroundImage = bitmap;
// 計算圖片中不透明部分的邊界 (建議用 Gif 圖片 )
GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
// 建立區域 ( Region )
form.Region = new Region(graphicsPath);
}
// 處理按鈕 ( button 類別 )
else if(control is System.Windows.Forms.Button)
{
// control object 轉成 Button object 類別
Button button = (Button)control;
// 清除 Button 上面的文字
button.Text = "";

// 更改鼠標樣式是手狀鼠標
button.Cursor = Cursors.Hand;
// 設定背景圖樣
button.BackgroundImage = bitmap;

//計算圖片中不透明部分的邊界 (建議用 Gif 圖片 )
GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
// 建立區域 ( Region )
button.Region = new Region(graphicsPath);
}
// 這裡你可以模仿 Form 或者 Button 建立心的類別出歷程序, 比如Panel
}
// 計算圖片不透明區域 返回 GraphicsPath
private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
{
// 建立GraphicsPath, 給我們的位圖路徑計算使用
GraphicsPath graphicsPath = new GraphicsPath();
// 使用左上角 (0,0) 點作為透明色
// 如果這裡是紅色, 那麼我們計算是圖片中不包含紅色區域路徑
Color colorTransparent = bitmap.GetPixel(0, 0);
// 存儲第一個不透明點, 這個值決定我們開始檢查不透明區域.
int colOpaquePixel = 0;
// 檢查所有的行 ( Y axis )
for(int row = 0; row < bitmap.Height; row ++)
{
// 重置 colOpaquePixel 值
colOpaquePixel = 0;
// 檢查所有的列 ( X axis )
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
graphicsPath.AddRectangle(new Rectangle(colOpaquePixel,
row, colNext - colOpaquePixel, 1));
// 找到之後不用搜索不透明點
col = colNext;
}
}
}
// 返回計算出來的不透明圖片路徑
return graphicsPath;
}
產生不規則窗體<