【问题标题】:How to make a UserControls BackColor transparent in C#?如何在 C# 中使 UserControls BackColor 透明?
【发布时间】:2017-10-06 02:59:01
【问题描述】:

我在 Windows 窗体用户控件(由一个单选按钮和三个标签和一个进度条组成)中创建了一个简单的火柴人。

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

图片如下:

【问题讨论】:

  • 地铁?表格? WPF?银光?视窗电话? ASP.NET?单触?
  • Windows 窗体,Visual Studio 2010

标签: c# user-controls drawing


【解决方案1】:

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

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

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

【讨论】:

  • 太棒了!太棒了(^_^)。非常感谢先生:)
  • 顺便问一下,类似的问题请看这里:stackoverflow.com/questions/14373292/…
  • 我不会试图猜测为什么将已经为真的属性设置为 true 会有所作为。这需要正确记录,请单击按钮。
  • @Hans VS 2012,WinForms:如果您在 UserControl 构造函数中设置断点,并使用 GetStyle 在命令窗口中查看 SupportsTransparentBackColor 属性的值:则为“真”。如果在调用 InitializeComponent() 之后,在 UserControl 构造函数中将 Property 显式设置为 'true;与省略调用或将其放在 InitializeComponents() 之前相比,UserControl 元素的显示方式将完全不同; ...由于其局限性和“怪癖”,我很少在 WinForms/UserControls 中使用透明度。
  • @Hans Passant,我将 usercontrol 添加为 elementHost1.Parent = this; elementHost1.BackColor = 颜色.透明; elementHost1.Size = this.Size; elementHost1.Location = this.Location;但是用户控件显示不透明,请建议。
【解决方案2】:

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

SetStyle(ControlStyles.SupportsTransparentBackColor, true);

然后将背景设置为透明色

this.BackColor = Color.Transparent;

来自MSDN

一种更复杂的方法(并且可能有效)是described here - 覆盖CreateParamsOnPaint

【讨论】:

  • 谢谢,但这似乎扭曲了控制!见:upload.ustmb.ir/uploads/13_1313580995401.jpg
  • 让我走上了正确的道路。使用样式{不透明度:0.4;过滤器:alpha(不透明度=40); }
  • @Anthony Horne - 看起来像 CSS,而不是 C#/WinForms
  • @GeorgeBirbilis - 不是,但是是什么让你这么说?也许是 var?
  • @Anthony Horne 我的意思是过滤器:alpha(opacity=40)
【解决方案3】:

为什么会有这些东西? 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);
    }

}

结果如下图:

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

【讨论】:

  • 是的,很晚了,但我很欣赏这个答案;)
  • 不幸的是,我在 Stackoverflow 上不是很活跃。希望它现在会改变:)即使为时已晚,我希望这是您将从我的回答中学到的新的不同方法:P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 2021-01-19
  • 2014-01-19
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
相关资源
最近更新 更多