tags:

views:

87

answers:

2

Hello guys grls,

I have a standard picture box control with an image on it. I want to add half-transparent layer. It will not hide an image, it will be some kind of filter.

How can I do it ?

A: 

You can register the Paint event and write some code like this:

private void pictureBox1_Paint (object sender, PaintEventArgs e)
    {
      e.Graphics.FillRectangle (Brushes.Transparent, 0, 0, pictureBox1.Width, pictureBox1.Height);
    }

You need to genereate a semi-transparent brush (change the alpa-level of the needed color)

more information about custom painting in controls can be found in MSDN

This is just a small code snippet. To use Print events and the Graphics object correctly read the MSDN stuff first.

crauscher
The code above doesn't affect on image located on picturebox.. It affects only on background of picture box ...
Alexander Stalt
There is not that big difference between my answer and the accepted one.
crauscher
A transparent brush is the same as a null brush. In the code sample provided, it's not going to affect the image on the picture box. While your answer stated that Alexander should use a semitransparent brush, it's not clear from the sample *how* to create it. :-)
Mike J
A: 

The code would be similar to this:

private void pictureBox1_Paint (object sender, PaintEventArgs e)
{
   using (SolidBrush b = new SolidBrush(Color.FromArgb(128, Color.White))
   {
       e.Graphics.FillRectangle (b, 0, 0, pictureBox1.Width, pictureBox1.Height);
   }

However, the code above simply using a single color brush whose opactity is set to 128. There are other brush classes available, such as LinearGradientBrush, TextureBrush, PAthGradientBrush and HatchBrush.

Recommendation To paint custom effects like you want to (for a button pressed state), a recommended approach would be to generate pre-rendered images that you can create either at runtime of your application or using an external program such as Adobe Photoshop and then save these images.

Then the painting code would simply take the image that represents the current state of your "button" and draw that image in the overriden pictureBox1_Paint method.

This technique results in better graphics painting performance as opposed to simply repainting the same states at different state-change times in the application.

Mike J
I already have pre-rendered images. I store them in resources file.Thanks for an input. I will use your code. BTW, do you know how to create a picturebox with a lineargradientbrush which looks like title bar ? I tried several times but no result ...
Alexander Stalt
Hi Alexander, well the colors for a title bar can be found in SystemColors.ActiveCaption and SystemColors.InactiveCaption. Just curious, do you want to mimic a button in the window caption bar? If so, you still have to manage all the relevant windows messages, but to draw one, take a look at ControlPaint.DrawCaptionButton.
Mike J