Winform设计不规则窗体

创建不规则窗体,首先需要设计一个透明部分的 alpha值小于10的图片,推荐PNG格式

        ///<summary>
/// 设置不规则窗体
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void Login_Load(object sender, EventArgs e)
{
//从指定的位图中获取alpha透明度大于 10 的区域
Bitmap img = (Bitmap)pictureBox1.Image;
GraphicsPath grapth = GetNoneTransparentRegion(img, 10);
this.Region = new Region(grapth);

//要显示的图片设置为窗体背景
this.BackgroundImage = pictureBox1.Image;
this.BackgroundImageLayout = ImageLayout.Zoom;

//在修改窗体尺寸之前设置窗体为无边框样式
this.FormBorderStyle = FormBorderStyle.None;
this.Width = pictureBox1.Image.Width;
this.Height = pictureBox1.Image.Height;
}

///<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;
}

 

posted @ 2011-11-28 11:24  Yao,Mane  阅读(530)  评论(0编辑  收藏  举报