views:

46

answers:

2

Hi all,

I've created a custom panel (inherited from Panel) that override OnPaint method to paint the inner rectangle with LinearGradientBrush.

 public void PaintPanel()
 {
        // Re-calculate the 
        CalculatePanelHeight(); 
        Graphics _g = this.CreateGraphics();

        Point _startPoint = new Point(0, m_TopAreaHeight);
        Size _size = new Size(Width, m_BtmAreaHeight);
        Rectangle _btmRect = new Rectangle(_startPoint, _size);
        LinearGradientBrush _btmGradBrush = new LinearGradientBrush(_btmRect,                     BackColorBottom, BackColorBottom2, LinearGradientMode.Vertical);
        _btmGradBrush.GammaCorrection = true;
        _g.FillRectangle(_btmGradBrush, _btmRect);
        ...
 }

  protected override void OnPaint(PaintEventArgs e)
  {
        PaintPanel();
        base.OnPaint(e);
  }

However there're 2 quirks: 1) Whenever any control with transparent background is dragged into the custom panel, its background becomes White.

2) my custom panel doesn't support transparent background (the color turns to White whenever I set one of the gradient color to transparent).

Would anyone offers some insights please?

Thank you.

A: 

True transparency doesn't exist in Windows Forms. It is a Windows restriction, it doesn't support it on child windows. There are a few workaround tricks for it, like the WS_EX_TRANSPARENT window style and some support built into winforms for a BackColor that's transparent. They both work by asking the parent of the control to draw itself in the control window, providing the background pixels.

This breaks down when you start to overlap controls, you see the background of the parent (the form usually), not the overlapped control. And if your form's BackColor is white then you'll indeed see white, not the gradient of the intermediate control.

There's no practical workaround for this. If you want true transparency then you should consider WPF. It doesn't use windows, just layers of paint. Transparency is now trivial, just don't draw.

Hans Passant
A: 

Thanks Hans.

Sorry as I'm unable to leave a comment so I'll do it here.

  • I've noticed that whenever I drag a Panel into another Panel, its background color property will follow its parent.

Even if I reset it to Transparent, it will still renders the parent's color correctly.

How do those panels achieve those behaviors?

Are the .net Panel with transparent color will inherently refers to the colors of parent's pixels of overlapping area and repaint itself during OnPaint?

Willie Son
I explained this in my answer, "you see the background of the parent".
Hans Passant