[C#]半透明なPictureBox
クラスfadePictureBoxをPictureBoxを派生させて作っています。使い方はこんな感じ。
private void button1_Click(object sender, EventArgs e) { fadePictureBox fp = new fadePictureBox(Properties.Resources.pic2); fp.Width = 240; fp.Height = 240; fp.Top = 30; fp.Left = 30; this.Controls.Add(fp); fp.Show(1000); //1000ms表示したら消える }
半透明を実現している方法は簡単だが強引。表示の前に表示する場所の背景画像をキャプチャし、表示対象とアルファブレンドします。
/// <summary> /// アルファブレンドした画像を描写する /// </summary> /// <param name="img">ブレンドする画像。背景bgImageはgetBackGroundImage()で取得済</param> /// <param name="alpha">透過値。0~1の間</param> private void DrawBrendImage(Image img, float alpha) { //ブレンドして表示する背景を準備 Bitmap brendBmp = (Bitmap)bgImage.Clone(); Graphics brendG = Graphics.FromImage(brendBmp); //System.Drawing.Imaging.ColorMatrixオブジェクトの作成 //ColorMatrixの行列の値を変更して、アルファ値がalphaに変更されるようにする ColorMatrix cm = new ColorMatrix(); cm.Matrix00 = 1; cm.Matrix11 = 1; cm.Matrix22 = 1; cm.Matrix33 = alpha; cm.Matrix44 = 1; //System.Drawing.Imaging.ImageAttributesオブジェクトの作成 //ColorMatrixを設定、ImageAttributesを使用して背景に描画 ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); //アルファブレンドしながら描写 brendG.DrawImage( img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia); //合成された画像を表示 using (Graphics g = this.CreateGraphics()) { g.DrawImage(brendBmp, 0, 0); } //リソースを開放する brendG.Dispose(); brendBmp.Dispose(); } /// <summary> /// 背景となる画像を取得する。 /// 取得した画像はbgImageに保存。 /// </summary> private void getBackGroundImage() { //表示位置の背景を取得 Rectangle rc; rc = this.RectangleToScreen(new Rectangle(0, 0, this.Width, this.Height)); bgImage = new Bitmap( rc.Width, rc.Height, PixelFormat.Format32bppArgb ); using (Graphics gBgImage = Graphics.FromImage(bgImage)) { gBgImage.CopyFromScreen( rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy); } }
| 固定リンク


コメント