在 Windows 窗体中,您可以通过定义区域来实现透明度(或绘制不规则形状的窗口)。引用MSDN
窗口区域是窗口内像素的集合,其中
操作系统允许绘图。
就您而言,您应该有一个将用作遮罩的位图。位图应该至少有两种不同的颜色。其中一种颜色应代表控件中您希望透明的部分。
然后您将创建一个如下所示的区域:
// this code assumes that the pixel 0, 0 (the pixel at the top, left corner)
// of the bitmap passed contains the color you wish to make transparent.
private static Region CreateRegion(Bitmap maskImage) {
Color mask = maskImage.GetPixel(0, 0);
GraphicsPath grapicsPath = new GraphicsPath();
for (int x = 0; x < maskImage.Width; x++) {
for (int y = 0; y < maskImage.Height; y++) {
if (!maskImage.GetPixel(x, y).Equals(mask)) {
grapicsPath.AddRectangle(new Rectangle(x, y, 1, 1));
}
}
}
return new Region(grapicsPath);
}
然后,您可以将控件的区域设置为 CreateRegion 方法返回的区域。
this.Region = CreateRegion(YourMaskBitmap);
删除透明度:
this.Region = new Region();
从上面的代码中您可能可以看出,创建区域在资源方面是昂贵的。如果您需要多次使用它们,我建议将区域保存在变量中。如果您以这种方式使用缓存区域,您很快就会遇到另一个问题。该分配第一次会起作用,但在后续调用中您会收到 ObjectDisposeException。
使用reflector进行一些调查会发现 Region 属性的 set 访问器中存在以下代码:
this.Properties.SetObject(PropRegion, value);
if (region != null)
{
region.Dispose();
}
Region对象在使用后被丢弃!
幸运的是,区域是可克隆的,您需要做的就是分配一个克隆来保留区域对象:
private Region _myRegion = null;
private void SomeMethod() {
_myRegion = CreateRegion(YourMaskBitmap);
}
private void SomeOtherMethod() {
this.Region = _myRegion.Clone();
}