Title: Make a button display the picture beneath slightly grayed it in C#
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 the example to experiment with it and to see additional details.
|