我有一个用户界面,需要在 C# 项目中放置一些圆形按钮,并在它们后面放置一些数据。这些按钮是 System.Windows.Forms.buttons,我使用了具有透明度的 GIF 图像来创建它们。但是,透明区域不透明。我在网上查找了参考资料,但没有找到有关如何正确执行此操作的任何建议。有人提到在 Visual Studio 2008 中这样做,但我需要在 2005 年保留这个项目。感谢任何帮助或建议。
8 回答
只需将 Button 的FlatStyle 属性设置为“Flat”……瞧!我知道这适用于 PNG,但我还没有用 GIF 测试过。
我很确定您需要使用带有 WinForms 的 PNG 来获得图像透明度。我知道我已经成功地使用了它们。
编辑:当我使用 PNG 时,我将它们与 Image 控件叠加到 Form1.BackgroundImage 上;我没有在按钮中使用它们。
我认为你最好的选择是从使用按钮控件切换到使用图像控件。您也可以尝试将按钮样式更改为扁平(我认为它是扁平的,也许是其他样式之一),看看您是否可以通过这种方式获得您想要的效果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
public class TransparentControl : Control
{
public TransparentControl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
SetStyle(ControlStyles.ResizeRedraw, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// don't call the base class
//base.OnPaintBackground(pevent);
}
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TRANSPARENT = 0x20;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
// rest of class here...
}
尝试这个:
Bitmap temp = new Bitmap(button1.Image);
temp.MakeTransparent(Color.Black); //your transparent color, in this case black
button1.Image = (Image) Logo;
temp.Dispose();
temp = null;
以下答案在 Visual Studio 2012 中得到验证,适用于 backgroundImage 格式 BMP、GIF、PNG 以及 JPG;由 MS Paint 创建。
通过按钮使背景可见:
转到按钮的属性窗口。然后更改 FlatStyle 和 BackColor,如下图所示:
注意:颜色要从 Web 选项卡中选择,而平面样式要选择为平面。
但在此之后,按钮将是透明的,直到鼠标不悬停或被选中或按下。在这种情况下,它将是一些不透明的颜色。如果你想让它总是透明的,按照下面的图片,像以前一样把对应的颜色改成透明的。要更改的颜色是:“MouseOverBackColor”和“MouseDownBackColor”。
注意:如果您选择始终透明,如图所示,按钮的外观将不会发生变化,同时它会起作用!
希望它会帮助你。
祝你好运!
您需要将按钮的 BackColor 属性设置为“透明”。
Button1.BackColor = System.Drawing.Color.Transparent;
创建一个从按钮派生的类并放置此代码。
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TRANSPARENT = 0x20;
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT;
return cp;
}
}
并在创建方法中
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
this.BackColor = Color.Transparent;
我正在使用 Visual Studio 2005 并尝试按照上面的示例进行操作,但它不起作用(创建方法中的片段)。我的表单有背景,并且正在尝试创建斜面透明按钮。
当前插入上面的代码使我的背景透明,我的按钮全是白色的。
这是我的代码片段
Bitmap mainFormBackground = (Bitmap)Image.FromFile("background.jpg");
this.BackgroundImage = mainFormBackground;
this.BackColor = Color.Black;
this.ForeColor = Color.White;
添加一些按钮
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
this.BackColor = Color.Transparent;
我什至试过
btnName.BackColor = Color.Transpare;
这也行不通