Make a button display the picture beneath slightly grayed it in C#

[button]

The example Make a button display the picture beneath it in C# shows how to make a button display the picture that lies below it. Unfortunately, the button only adds a border as decoration and the border doesn’t have a very three-dimensional appearance, so it can be hard to see. It may also be difficult to see the button’s text on top of the picture.

This example modifies the SetButtonBackground method to allow you to add some gray to the button’s image. That makes it much easier to see.


The following code shows the modified version of the SetButtonBackground method. The new code is highlighted in blue.

// Make the Button display the part of the
// PictureBox's picture that is under it.
private void SetButtonBackground(PictureBox pic, Button btn, byte alpha)
{
    // Get the offset between the PictureBox's
    // and button's upper left corners.
    Point pic_pt = new Point(0, 0);
    pic_pt = pic.PointToScreen(pic_pt);
    Point btn_pt = new Point(0, 0);
    btn_pt = btn.PointToScreen(btn_pt);
    int x_offset = btn_pt.X - pic_pt.X;
    int y_offset = btn_pt.Y - pic_pt.Y;

    // Get the button's size.
    int wid = btn.ClientSize.Width;
    int hgt = btn.ClientSize.Height;

    // Make a bitmap to hold the button image.
    Bitmap bm = new Bitmap(wid, hgt);
    using (Graphics gr = Graphics.FromImage(bm))
    {
        // Destination rectangle.
        Rectangle dest_rect = new Rectangle(0, 0, wid, hgt);

        // Source rectangle.
        Rectangle src_rect = new Rectangle(x_offset, y_offset, wid, hgt);

        // Copy the image under the button into the bitmap.
        gr.DrawImage(pic.Image, dest_rect, src_rect, GraphicsUnit.Pixel);

        // Draw some gray over the image.
        Color color = Color.FromArgb(alpha, Color.White);
        using (Brush brush = new SolidBrush(color))
        {
            gr.FillRectangle(brush, dest_rect);
        }
    }

    // Make the button display the image.
    btn.Image = bm;
}

The method works mostly as it did before. After it copies the part of the image below the button into a new image, the method draw a translucent white rectangle over the image. It uses its alpha parameter to determine how opaque the rectangle is. Use a large alpha value (closer to 255) to make the button more gray. Use a small values (close to 0) to make the button less gray.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

This entry was posted in controls, graphics, image processing and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *