C#中級 コーディング例
G5)画像半透明化
画像(ビットマップ)を半透明化加工して、返します。
//source:対象ビットマップ画像
//alpha:透明度合
public static Bitmap FadeImage(Bitmap source, float alpha)
{
// alpha: 0.0 = 完全透明, 1.0 = 元のまま
//カラーマトリックスのアルファーチャンネルを設定
var cm = new ColorMatrix
{
Matrix33 = alpha
};
//レンダリング時のビットマップの色の操作方法に関する情報を格納します
var ia = new ImageAttributes();
ia.SetColorMatrix(cm);
var outputBmp = new Bitmap(source.Width, source.Height);
//ImageAttributes オブジェクトを、Graphics オブジェクトの DrawImage メソッドに渡します
using (var g = Graphics.FromImage(outputBmp)
{
g.DrawImage(
source,
new Rectangle(0, 0, source.Width, source.Height),
0, 0, source.Width, source.Height,
GraphicsUnit.Pixel,
ia
);
}
return outputBmp
}

元画像

半透明画像