使用以下代码示例实现半透明窗体背景:
在窗体的构造函数中添加以下代码:
this.BackColor = Color.FromArgb(128, 0, 0, 0);
注:代码中的数字 128 表示透明度。范围从 0(完全透明)到 255(完全不透明)。
如果需要在窗体上显示半透明图像,可以使用以下代码:
private void Form1_Paint(object sender, PaintEventArgs e) { Image image = Image.FromFile("image.png"); // 要显示的图像文件路径 e.Graphics.DrawImage(image, new Rectangle(0, 0, this.Width, this.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, GetImageAttributes()); }
private ImageAttributes GetImageAttributes() { ColorMatrix matrix = new ColorMatrix(); matrix.Matrix33 = 0.5f; // 控制图像的透明度,范围从 0 到 1,此处设为半透明 ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); return attributes; }
注:代码中的图片文件路径需要根据实际情况修改。