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 _startP开发者_JAVA技巧oint = 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:
Whenever any control with transparent background is dragged into the custom panel, its background becomes White.
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.
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.
精彩评论