In winforms you will have to modify the alpha of the PictureBox.Image
.
To do that in a fast way use a ColorMatrix
!
Here is an example:
The trackbar code:
Image original = null;
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (original == null) original = (Bitmap) pictureBox1.Image.Clone();
pictureBox1.BackColor = Color.Transparent;
pictureBox1.Image = SetAlpha((Bitmap)original, trackBar1.Value);
}
To use a ColorMatrix
we need this using clause:
using System.Drawing.Imaging;
Now for the SetAlpha
function; note that it is basically a clone from the MS link..:
static Bitmap SetAlpha(Bitmap bmpIn, int alpha)
{
Bitmap bmpOut = new Bitmap(bmpIn.Width, bmpIn.Height);
float a = alpha / 255f;
Rectangle r = new Rectangle(0, 0, bmpIn.Width, bmpIn.Height);
float[][] matrixItems = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, a, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
using (Graphics g = Graphics.FromImage(bmpOut))
g.DrawImage(bmpIn, r, r.X, r.Y, r.Width, r.Height, GraphicsUnit.Pixel, imageAtt);
return bmpOut;
}
Note the the ColorMatrix
expects its elements to be be scaling factors with 1
being the identity. The TrackBar.Value
goes from 0-255
, just like a Bitmap
alpha channel..
Also note that the function creates a new Bitmap
, which may lead to GDI
leaking. Here the PictureBox
takes care of it, it seems; at least testing it with the taskmanger ('Details' - turn on GDI-objects column!) shows no problems :-)
Final note: This will work if and only if the PictureBox
is nested in the control 'behind' it! If it merely overlaps this will not work!! In my example it sits on a TabPage
, which is a Container
and anything you drop on it gets nested inside. It would work the same if I had dropped it onto a Panel
. But PictureBoxes
are no containers. So if you want another PictureBox
to show up behind it, then you need code to create the nesting: pboxTop.Parent = pBoxBackground; pboxTop.Location = Point.Empty;