在C# Winfrom项目中,如何将form窗体由矩形绘制成圆形。
请帮忙看看如何设置form窗体,可以达到下面截图中的圆形效果。谢谢!
最好能够与截图中的圆形做得十分接近(圆形的背景色、字体、线条等)。
使用protected override void OnPaint(PaintEventArgs e),将窗体进行重绘。就可以将窗体改成想要的样子。
有没有相关绘制圆形的参考资料。
Winform窗体通常都是矩形的,而本人在需要将一幅图片作为窗体背景,并且窗体边框呈现为图片外轮廓的不规则边缘时,却发现Framework并没有提供直接的实现。经过一通百度、Google和查阅 MSDN 后,发现实现的途径主要有以下几种:
覆盖 Form 本身的绘制,自己用代码重绘。
设置窗体的 TransparencyKey 为窗体设置背景图片边缘要成为不规则边框的部分的颜色。
根据图片或者其它的方式创建不规则的 GraphicPath 生成 Region,指定给窗体的 Region 属性。
这三种方法各有优劣:
第1种最麻烦,因为要靠代码一点点抠,要达到良好效果不容易,也不易于以后的修改。
第2种最简单,但有制约条件:a、图片的边缘部以外必须是TransparencyKey指定的颜色,并且图片的其它部分不能有这种颜色,否则会被不加区分的变为透明,而导致窗体出现镂空。b、系统必须运行在 24 位色下。因此,这种方法并不实用。
第3种的复杂程度介于1、2之间,并且控制也比较灵活。故本人选择了这种实现方式。
对于第3种方法,网上大多数的文章都只是介绍了实现的原理和一些简单的 Demo 代码。直接照做可能会遇到以下的一些问题而影响显示效果:
窗体的边缘和作为背景的图片外轮廓不重叠,出现错位。
界面上的控件布局时不容易定位于背景图片的相对位置。
解决这两个问题很简单,是要注意一些操作的细节。先看实现代码:
复制代码
不规则窗体的实现
1 //从指定的位图中获取透明度大于 10 的区域;
2 Bitmap img = (Bitmap)pictbox.Image;
3 GraphicsPath grapth = BitmapUtil.GetNoneTransparentRegion(img, 10);
4 this.Region = new Region(grapth);
5
6 //要显示的图片设置为窗体背景;
7 this.BackgroundImage = pictbox.Image;
8 this.BackgroundImageLayout = ImageLayout.Zoom;
9
10 //在修改窗体尺寸之前设置窗体为无边框样式;
11 this.FormBorderStyle = FormBorderStyle.None;
12 this.Width = pictbox.Image.Width;
13 this.Height = pictbox.Image.Height;
复制代码
BitmapUtil.GetNoneTransparentRegion 方法的实现如下:
复制代码
读取位图的非透明区域
1 ///
2 /// 返回指定图片中的非透明区域;
3 ///
4 /// 位图
5 /// alpha 小于等于该值的为透明
6 ///
7 public static GraphicsPath GetNoneTransparentRegion(Bitmap img, byte alpha)
8 {
9 int height = img.Height;
10 int width = img.Width;
11
12 int xStart, xEnd;
13 GraphicsPath grpPath = new GraphicsPath();
14 for (int y = 0; y < height; y++)
15 {
16 //逐行扫描;
17 for (int x = 0; x < width; x++)
18 {
19 //略过连续透明的部分;
20 while (x < width && img.GetPixel(x, y).A <= alpha)
21 {
22 x++;
23 }
24 //不透明部分;
25 xStart = x;
26 while (x < width && img.GetPixel(x, y).A > alpha)
27 {
28 x++;
29 }
30 xEnd = x;
31 if (img.GetPixel(x - 1, y).A > alpha)
32 {
33 grpPath.AddRectangle(new Rectangle(xStart, y, xEnd - xStart, 1));
34 }
35 }
36 }
37 return grpPath;
38 }
复制代码
以上的代码中,解决边框与背景出现错误的办法是“在修改窗体尺寸之前设置窗体为无边框样式”,因为,窗体的长宽是包含在窗体标题栏的尺寸的,而背景显示图片的工作区是除去窗体标题栏的。
解决在设计时“界面控件在背景图片上的布局问题”可以也很简单,通过一些操作技巧就可以达到,具体如下:
设计窗体时,通过Visual Studio窗体设计器将背景图片设置为窗体背景,将 BackgroundImageLayout 属性设为 Zoom,这样就能在设计时观察到背景。
采用 TableLayoutPanel 面板进行布局,布局上采用相对尺寸。控件布局在网格之中,网格的行列的宽度值都按百分比定位。这样就不需要关注窗体显示尺寸的绝对值,在实际显示的时候,哪怕窗体大小发生改变,界面上控件与背景图片的相对位置也能保持设计时的相对定位。
现在,C#创建不规则窗体不是一件难事,下面总结一下:
一、自定义窗体,一般为规则的图形,如圆、椭圆等。
做法:重写Form1_Paint Event (Form1是窗体的名字),最简单的一种情况如下:
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
shape.AddEllipse(0,0,this.Height, this.Width);
this.Region = new Region(shape);
即重绘窗体的规则。
二、利用背景图片实现
这种做法的不好的地方就是背景图片一定要16位或者更低的,而且还要确保客户端的显示。如果监视器的颜色深度设置大于 24 位,则不管 TransparencyKey 属性是如何设置的,窗体的非透明部分都会产生显示问题。若要避免出现这种问题,请确保“显示”控制面板中的监视器颜色深度的设置小于 24 位。当开发具有这种透明功能的应用程序时,请牢记应使您的用户意识到此问题。
实现步骤如下:
1. 新建windows application
2. 选择窗体,找到BackgroundImage属性,点击打开新的窗口,选择下面的导入资源文件,选择你的不规则的BMP图片
3. 找到窗体的TansparencyKey,将它设置为你背景图片的背景色(如黄色)
4. 找到窗体的FormBorderStyle,将其设置为none,即不显示标题栏
5. 运行
实现步骤如下:
1. 建立winform应用程序
2. 找到窗体的Load Event ,双击进行编辑
3. 编写方法,主要的代码如下:
代码
class BitmapRegion
{
public BitmapRegion()
{ }
///
/// Create and apply the region on the supplied control
/// 创建支持位图区域的控件(目前有button和form)
///
/// The Control object to apply the region to控件
/// The Bitmap object to create the region from位图
public static void CreateControlRegion(Control control, Bitmap bitmap)
{
// Return if control and bitmap are null
//判断是否存在控件和位图
if (control == null || bitmap == null)
return;
// Set our control”s size to be the same as the bitmap
//设置控件大小为位图大小
control.Width = bitmap.Width;
control.Height = bitmap.Height;
// Check if we are dealing with Form here
//当控件是form时
if (control is System.Windows.Forms.Form)
{
// Cast to a Form object
//强制转换为FORM
Form form = (Form)control;
// Set our form”s size to be a little larger that the bitmap just
// in case the form”s border style is not set to none in the first place
//当FORM的边界FormBorderStyle不为NONE时,应将FORM的大小设置成比位图大小稍大一点
form.Width = control.Width;
form.Height = control.Height;
// No border
//没有边界
form.FormBorderStyle = FormBorderStyle.None;
// Set bitmap as the background image
//将位图设置成窗体背景图片
form.BackgroundImage = bitmap;
// Calculate the graphics path based on the bitmap supplied
//计算位图中不透明部分的边界
GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
// Apply new region
//应用新的区域
form.Region = new Region(graphicsPath);
}
// Check if we are dealing with Button here
//当控件是button时
else if (control is System.Windows.Forms.Button)
{
// Cast to a button object
//强制转换为 button
Button button = (Button)control;
// Do not show button text
//不显示button text
button.Text = ”";
// Change cursor to hand when over button
//改变 cursor的style
button.Cursor = Cursors.Hand;
// Set background image of button
//设置button的背景图片
button.BackgroundImage = bitmap;
// Calculate the graphics path based on the bitmap supplied
//计算位图中不透明部分的边界
GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
// Apply new region
//应用新的区域
button.Region = new Region(graphicsPath);
}
}
///
/// Calculate the graphics path that representing the figure in the bitmap
/// excluding the transparent color which is the top left pixel.
/// //计算位图中不透明部分的边界
///
/// The Bitmap object to calculate our graphics path from
/// Calculated graphics path
private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
{
// Create GraphicsPath for our bitmap calculation
//创建 GraphicsPath
GraphicsPath graphicsPath = new GraphicsPath();
// Use the top left pixel as our transparent color
//使用左上角的一点的颜色作为我们透明色
Color colorTransparent = bitmap.GetPixel(0, 0);
// This is to store the column value where an opaque pixel is first found.
// This value will determine where we start scanning for trailing opaque pixels.
//第一个找到点的X
int colOpaquePixel = 0;
// Go through all rows (Y axis)
// 偏历所有行(Y方向)
for (int row = 0; row < bitmap.Height; row++)
{
// Reset value
//重设
colOpaquePixel = 0;
// Go through all columns (X axis)
//偏历所有列(X方向)
for (int col = 0; col < bitmap.Width; col++)
{
// If this is an opaque pixel, mark it and search for anymore trailing behind
//如果是不需要透明处理的点则标记,然后继续偏历
if (bitmap.GetPixel(col, row) != colorTransparent)
{
// Opaque pixel found, mark current position
//记录当前
colOpaquePixel = col;
// Create another variable to set the current pixel position
//建立新变量来记录当前点
int colNext = col;
// Starting from current found opaque pixel, search for anymore opaque pixels
// trailing behind, until a transparent pixel is found or minimum width is reached
///从找到的不透明点开始,继续寻找不透明点,一直到找到或则达到图片宽度
for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)
if (bitmap.GetPixel(colNext, row) == colorTransparent)
break;
// Form a rectangle for line of opaque pixels found and add it to our graphics path
//将不透明点加到graphics path
graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1));
// No need to scan the line of opaque pixels just found
col = colNext;
}
}
}
// Return calculated graphics path
return graphicsPath;
}
}
4. 运行
三、调用类库实现
主要就是根据一些坐标,然后根据这些坐标绘制窗体
代码如下:
代码
public Form3()
{
InitializeComponent();
//创建不规则窗体
POINTAPI[] poin;
poin = new POINTAPI[5];
poin[0].x = 90;
poin[0].y = 90;
poin[1].x = this.Width;
poin[1].y = 0;
poin[2].x = Width;
poin[2].y = this.Height / 2;
poin[3].x = Width / 2;
poin[3].y = Height / 2;
poin[4].x = 0;
poin[4].y = Width;
Boolean flag = true;
IntPtr hRgn = CreatePolygonRgn(ref poin[0], 8, 1);
SetWindowRgn(this.Handle, hRgn, ref flag);
this.BackColor = Color.BurlyWood;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINTAPI
{
internal int x;
internal int y;
}
[DllImport("gdi32.dll")]
private static extern IntPtr CreatePolygonRgn(ref POINTAPI lpPoint,int nCount,int nPolyFillMode);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowRgn(IntPtr hWnd,IntPtr hRgn, ref Boolean bRedraw);
//设置窗体显示状态
[DllImport("user32.dll")]
private static extern int SetWindowPos(IntPtr hwnd,int hWndInsertAfter,int x,int y,int cx,int cy,int wFlags);
private void Start_Btn_Click(object sender, EventArgs e)
{//始终显示在前面
SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1);
}
private void button1_Click(object sender, EventArgs e)
{
//最小化始终显示在前面
SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 0);
}
当然,我们也可以自定义窗体的动作,如按着某个轨迹一定,下面的代码中的BackgroundForm程序中就小试了一下,效果还不错,下面是这些程序的效果图(有点乱)和代码:
不规则窗体代码下载:
http://files.cnblogs.com/alexis/IrregularForm.rar
对于采用第三种方式,效果可以实现。但是圆形的边框不平滑,有齿轮效果,怎么样做到圆形的边框平整圆滑的效果。
我采用的是圆形图片作为picturebox图形,代码如下,看看怎么修改下。
private void Form1_Load(object sender, EventArgs e)
{
//程序启动后,窗体在屏幕中央显示
this.Left = (SystemInformation.PrimaryMonitorMaximizedWindowSize.Width - this.Width) / 2;
this.Top = (SystemInformation.PrimaryMonitorMaximizedWindowSize.Height - this.Height) / 2;
//从指定的位图中获取透明度大于 10 的区域;
Bitmap img = (Bitmap)pictureBox1.Image;
GraphicsPath grapth = GetNoneTransparentRegion(img, 110);
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;
}