Windowsフォームでは、領域を定義することで透明性を実現します(または不規則な形状のウィンドウを描画します)。MSDNを引用するには
ウィンドウ領域は、オペレーティングシステムが描画を許可するウィンドウ内のピクセルのコレクションです。
あなたの場合、マスクとして使用するビットマップが必要です。ビットマップには、少なくとも2つの異なる色が必要です。これらの色の1つは、透明にしたいコントロールの部分を表す必要があります。
次に、次のようなリージョンを作成します。
// 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);
}
次に、コントロールのRegionをCreateRegionメソッドによって返されるRegionに設定します。
this.Region = CreateRegion(YourMaskBitmap);
透明度を削除するには:
this.Region = new Region();
上記のコードからわかるように、リージョンの作成はリソースの面でコストがかかります。リージョンを複数回使用する必要がある場合は、リージョンを変数に保存することをお勧めします。このようにキャッシュ領域を使用すると、すぐに別の問題が発生します。割り当ては最初は機能しますが、その後の呼び出しでObjectDisposedExceptionが発生します。
リフレクターを使って少し調査すると、Regionプロパティのセットアクセサー内に次のコードが表示されます。
this.Properties.SetObject(PropRegion, value);
if (region != null)
{
region.Dispose();
}
Regionオブジェクトは、使用後に破棄されます。幸い、Regionはクローン可能であり、Regionオブジェクトを保持するために必要なのは、クローンを割り当てることだけです。
private Region _myRegion = null;
private void SomeMethod() {
_myRegion = CreateRegion(YourMaskBitmap);
}
private void SomeOtherMethod() {
this.Region = _myRegion.Clone();
}