我正在使用 RoundRect GDI 函数按照以下示例绘制圆角矩形:.NET CF 自定义控件:RoundedGroupBox
因为所有的控件都是正方形的,所以它也在圆角矩形的外面画角。如何使矩形外的这个空间透明?
OnPaint 方法是:
protected override void OnPaint(PaintEventArgs e)
{
int outerBrushColor = HelperMethods.ColorToWin32(m_outerColor);
int innerBrushColor = HelperMethods.ColorToWin32(this.BackColor);
IntPtr hdc = e.Graphics.GetHdc();
try
{
IntPtr hbrOuter = NativeMethods.CreateSolidBrush(outerBrushColor);
IntPtr hOldBrush = NativeMethods.SelectObject(hdc, hbrOuter);
NativeMethods.RoundRect(hdc, 0, 0, this.Width, this.Height, m_diametro, m_diametro);
IntPtr hbrInner = NativeMethods.CreateSolidBrush(innerBrushColor);
NativeMethods.SelectObject(hdc, hbrInner);
NativeMethods.RoundRect(hdc, 0, 18, this.Width, this.Height, m_diametro, m_diametro);
NativeMethods.SelectObject(hdc, hOldBrush);
NativeMethods.DeleteObject(hbrOuter);
NativeMethods.DeleteObject(hbrInner);
}
finally
{
e.Graphics.ReleaseHdc(hdc);
}
if (!string.IsNullOrEmpty(m_roundedGroupBoxText))
{
Font titleFont = new Font("Tahoma", 9.0F, FontStyle.Bold);
Brush titleBrush = new SolidBrush(this.BackColor);
try
{
e.Graphics.DrawString(m_roundedGroupBoxText, titleFont, titleBrush, 14.0F, 2.0F);
}
finally
{
titleFont.Dispose();
titleBrush.Dispose();
}
}
base.OnPaint(e);
}
OnPaintBackground 是:
protected override void OnPaintBackground(PaintEventArgs e)
{
if (this.Parent != null)
{
SolidBrush backBrush = new SolidBrush(this.Parent.BackColor);
try
{
e.Graphics.FillRectangle(backBrush, 0, 0, this.Width, this.Height);
}
finally
{
backBrush.Dispose();
}
}
}
谢谢!
最佳答案
使用标准托管操作时,您需要将“外部”颜色(圆形部分之外的颜色)设为特定颜色(洋红色是常见颜色),然后使用 SetColorKey将该颜色设置为透明。
This MSDN article了解如何实现它。
编辑 1
由于您正在 P/Invoking 您的 GDI 操作,因此您也可以继续这样做。如果您正在绘制带有透明度信息的图像,则可以使用 alpha blending ,但在这种情况下,您需要将整个“按钮”绘制到一个单独的缓冲区,然后 P/Invoke MaskBlt将其复制到表单的 DC(这是当您使用 colorkey 透明度时 CF 正在做的事情)。 Here's a desktop example , 但过程是一样的。
关于c# - 紧凑型框架上的 GDI RoundRect : make rounded rectangle's outside transparent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1445353/