如何在C#中使UserControls BackColor透明化?

时间:2013-01-13 17:12:03

标签: c# user-controls drawing

我在Windows窗体用户控件中创建了一个简单的操作员(包含一个单选按钮和三个标签以及一个进度条)。

我将新用户控件的背景颜色设置为透明,这样当我将其拖到我的表单上时,它会与表单上的其他颜色和绘图混合。 我没有得到我想要达到的目标。

这是图片:

enter image description here

3 个答案:

答案 0 :(得分:11)

UserControl已经支持此功能,其ControlStyles.SupportsTransparentBackColor样式标志已经打开。您所要做的就是将BackColor属性设置为Color.Transparent。

接下来你需要记住,这个透明度是模拟的,它是通过要求控件的Parent绘制自己来产生背景来完成的。所以重要的是你正确设置了Parent。如果父级不是容器控件,那么这有点棘手。像PictureBox一样。设计人员将表格作为父母,这样您就可以看到表格的背景,而不是图片框。您需要在代码中修复它,编辑表单构造函数并使其看起来类似于:

var pos = this.PointToScreen(userControl11.Location);
userControl11.Parent = pictureBox1;
userControl11.Location = pictureBox1.PointToClient(pos);

答案 1 :(得分:4)

在构造函数中设置控件样式以支持透明背景颜色

SetStyle(ControlStyles.SupportsTransparentBackColor, true);

然后将Background设置为transperent color

this.BackColor = Color.Transparent;

来自MSDN

更复杂的方法(可能还有一个方法)是described here - 覆盖CreateParamsOnPaint

答案 2 :(得分:1)

为什么要这些东西? UserControl类具有属性Region。 将此设置为您喜欢的形状,无需进行其他调整。

public partial class TranspBackground : UserControl
{
    public TranspBackground()
    {
        InitializeComponent();
    }

    GraphicsPath GrPath
    {
        get
        {
            GraphicsPath grPath = new GraphicsPath();
            grPath.AddEllipse(this.ClientRectangle);
            return grPath;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // set the region property to the desired path like this
        this.Region = new System.Drawing.Region(GrPath);

        // other drawing goes here
        e.Graphics.FillEllipse(new SolidBrush(ForeColor), ClientRectangle);
    }

}

结果如下图所示:

enter image description here 没有低级代码,没有调整,简单和干净。 但是有一个问题,但在大多数情况下,它可能无法检测到,边缘不平滑,抗锯齿也无济于事。 但解决方法相当容易。事实上,比所有那些复杂的背景处理要容易得多。

相关问题