【问题标题】:How to make the underlying control visible instead of form when set the trasparent backcolor设置透明背景色时如何使底层控件可见而不是窗体
【发布时间】:2016-04-13 11:21:27
【问题描述】:

我在表单中添加了两个自定义控件,一个控件放置在另一个控件之上。将背景颜色设置为 control1 的透明,但它将背景颜色显示为表单颜色,而不是底层 control(control2) 颜色。请分享你的想法。提前致谢。

注意:例如,我提到了图片框,但是对于任何控件(例如 Richtextbox 或放置自定义控件)都会出现同样的问题。

图片链接:IssueImage

private void InitializeComponent()
{
    #region picturebox

    this.BackColor = Color.Aquamarine;
    this.WindowState = FormWindowState.Normal;            

    var selectBtn = new Button();
    selectBtn.Size = new Size(100, 30);
    selectBtn.Location = new Point(10, 10);
    selectBtn.Text = "Click";
    //selectBtn.Click += selectBtn_Click;

    var picturebox = new PictureBox();
    picturebox.Size = new Size(140, 110);
    picturebox.Location = new Point(4, 4);
    picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
    picturebox.Image = new Bitmap(@"..\..\Data\graphic1.png");            

    var picturebox2 = new PictureBox();
    picturebox2.Size = new Size(140, 110);
    picturebox2.Location = new Point(4, 4);
    picturebox2.SizeMode = PictureBoxSizeMode.StretchImage;
    picturebox2.Image = new Bitmap(@"..\..\Data\graphic1.png");

    graphiccell = new GraphicCellControl();
    graphiccell.Location = new Point(50, 200);
    graphiccell.BackColor = Color.Transparent;
    graphiccell.Size = new Size(160, 130);

    var graphiccell2 = new GraphicCellControl();
    graphiccell2.Location = new Point(100, 250);
    graphiccell2.BackColor = Color.Red;
    graphiccell2.Size = new Size(160, 130);
    // graphiccell2.BackColor = Color.Transparent;
    graphiccell.Controls.Add(picturebox);
    graphiccell2.Controls.Add(picturebox2);
    this.Controls.Add(graphiccell);
    this.Controls.Add(graphiccell2);
    this.Controls.Add(selectBtn);

    #endregion
}

public class GraphicCellControl : Control
{
    public GraphicCellControl()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    }       
}

【问题讨论】:

  • 为什么不设置控件的可见性而不是使其透明?
  • 不,我必须部分显示控件。请参考附图
  • @zohar Peled - 感谢您的更新,如果图片框位于另一张图片上,它可以正常工作,但如果图片框位于其他控件(例如richtextbox)上,则它不起作用

标签: c# .net winforms


【解决方案1】:

Windows 窗体中的透明度遵循 Windows 窗口的规则(呃)。这意味着默认情况下,只有在处理父子关系时才能获得“适当的”透明度。透明控件后面的控件只有如果它们是所述透明控件的父级,才会被绘制。

如果由于某种原因这对您来说不可行,您始终可以覆盖 OnPaintOnPaintBackground 方法,并显式渲染您需要渲染的任何控件,而不管父子关系如何。当然,如果你不能做一些简化的假设,你很快就会发现为什么默认情况下不这样做:)

没有任何可能的简化时,您需要做的快速列表:

  1. 查找透明控件后面的控件 - 当没有任何空间分区(如提到的父子关系)时,这尤其棘手
  2. 在当前控件的表面上按从后到前的顺序从 1. 渲染控件的相关表面
  3. 最好确保所有重叠的透明控件避免多次渲染相同的控件
  4. 确保所有可能更改透明控件背景的操作都会导致透明控件背景失效(并因此重新渲染)

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多