📜  c# picturebox transparente - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.575000             🧑  作者: Mango

C# PictureBox Transparency

The PictureBox control in C# allows us to display images in our Windows Forms applications. Sometimes, we may want to make a certain portion of the image transparent to show the contents beneath it. In this tutorial, we will discuss how to make a PictureBox control transparent in C#.

Setting PictureBox Transparency

To make the PictureBox control transparent, we need to set its BackColor property to Color.Transparent. The BackColor property is a property of the Control class, which is the base class for all controls in C#.

pictureBox1.BackColor = Color.Transparent;

By setting the BackColor property to Color.Transparent, the PictureBox control will show the contents beneath it. However, this alone will not make the image in the PictureBox control transparent.

To make the image transparent, we need to set the PictureBox control's Image property to a transparent image. We can do this by creating a Bitmap with a transparent background, and then setting it as the Image property of the PictureBox control.

Bitmap bmp = new Bitmap(@"C:\path\to\image.png");
bmp.MakeTransparent(Color.White); // make white pixels transparent
pictureBox1.Image = bmp;

In the above code, we first load an image from a file using the Bitmap class. We then call the MakeTransparent method of the Bitmap class, passing in the color that we want to make transparent. In this example, we are making any white pixels in the image transparent.

Finally, we set the Image property of the PictureBox control to the transparent Bitmap. Now, any white pixels in the image will be transparent, allowing the contents beneath the control to show through.

Conclusion

In C#, we can make a PictureBox control transparent by setting its BackColor property to Color.Transparent, and then setting its Image property to a transparent Bitmap. This allows us to create more advanced user interfaces that show the contents beneath controls, making our applications more visually appealing.