另一个不需要使用新表单的解决方案:
- 制作容器(表单/面板/其他)的图像,
- 更改其不透明度,
- 在一个新面板的背景中显示它。
- 用该面板填充您的容器。
现在来看代码...
假设我有一个名为Frame的用户控件,我想要应用我的灯箱效果:
public partial class Frame : UserControl
{
private Panel shadow = new Panel();
private static float LIGHTBOX_OPACITY = 0.3f;
public Frame()
{
InitializeComponent();
shadow.Dock = DockStyle.Fill;
}
public void ShowLightbox()
{
Bitmap bmp = new Bitmap(this.Width, this.Height);
this.pnlContainer.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height));
shadow.BackgroundImage = SetImgOpacity(bmp, LIGHTBOX_OPACITY );
this.Controls.Add(shadow);
shadow.BringToFront();
}
private Image SetImgOpacity(Image imgPic, float imgOpac)
{
Bitmap bmpPic = new Bitmap(imgPic.Width, imgPic.Height);
Graphics gfxPic = Graphics.FromImage(bmpPic);
ColorMatrix cmxPic = new ColorMatrix();
cmxPic.Matrix33 = imgOpac;
ImageAttributes iaPic = new ImageAttributes();
iaPic.SetColorMatrix(cmxPic, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
gfxPic.DrawImage(imgPic, new Rectangle(0, 0, bmpPic.Width, bmpPic.Height), 0, 0, imgPic.Width, imgPic.Height, GraphicsUnit.Pixel, iaPic);
gfxPic.Dispose();
return bmpPic;
}
}
使用此技术的优点包括:
- 无需处理所有鼠标事件
- 无需管理多个表单以与灯箱元素通信
- 不需要覆盖WndProc
- 你会很酷,因为你是唯一一个不使用表单来实现这种效果的人。
缺点主要是这种技术速度较慢,因为您必须处理整个图像来使用ColorMatrix纠正每个像素点。