你知道在WPF中可以实现这个功能。但是我有一个在Windows Forms中的项目,我不想费力地将项目移植到WPF中。那么在Windows Forms中是否也能实现呢?(与另一个问题所问的不同,我不是要求面板的透明度。我是在问“如果我使用背景图像”,能否使其半透明。)
您需要尝试两件事情:将BackColor设置为透明,将图像转换为具有透明度的东西。
public Image SetImageOpacity(Image image, float opacity) {
Bitmap bmp = new Bitmap(image.Width, image.Height);
using (Graphics g = Graphics.FromImage(bmp)) {
ColorMatrix matrix = new ColorMatrix();
matrix.Matrix33 = opacity;
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
g.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height),
0, 0, image.Width, image.Height,
GraphicsUnit.Pixel, attributes);
}
return bmp;
}
panel1.BackColor = Color.Transparent;
panel1.BackgroundImage = SetImageOpacity(backImage, 0.25F);
不透明度只能在顶级窗口上工作。您无法在面板上使用不透明度。
如果您只想要带有不透明度的图片,我认为您可以自己绘制它,就像以下示例一样。 image
是 System.Drawing.Image 的一个实例。
using (Graphics g = Graphics.FromImage(image))
{
Pen pen = new Pen(Color.FromArgb(alpha, 255, 255, 255), image.Width);
g.DrawLine(pen, -1, -1, image.Width, image.Height);
g.Save();
}
编辑: 这篇文章也许会给你一些进一步的提示。此处链接
ElementHost
的方式,逐步将应用程序的部分移植到 WPF,而不是进行整体重构,或者如果你有多个Form
,你可以逐个将它们改为 WPFWindow
,逐步实现。 - Federico Berasategui