Make a button display the picture that is under it in C#

(Sorry for the holiday season slowdown. I won't be able to post as much for a little while yet.)

This example makes buttons display copies of the picture on which they sit, making it appear that the button is part of the underlying image. The key to this example is the following SetButtonBackground method.

// Make the Button display the part of the
// PictureBox's picture that is under it.
private void SetButtonBackground(
    PictureBox pic, Button btn)
{
    // 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);
    }

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

The method starts by using the PointToScreen method to determine where the upper left corner of the PictureBox and Button are in screen coordinates. This gives the relative offset between the two controls in pixels.

The code then gets the button's size, makes a Bitmap to fit it, and creates an associated Graphics object.

Next the method makes Rectangles to define the source and destination areas in the PictureBox's image that should be copied to the button. It then uses the Graphics object's DrawImage method to copy that part of the PictureBox's image into the new Bitmap. It finishes by making the Button display the new Bitmap.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.