我有一张在 Photoshop 中制作的透明图像,它的不透明度为 30%。
现在我试图把它作为面板的背景图像。但是普通面板即使将背景颜色设置为透明,也会显示白色/控制背景。面板不会变得透明。
所以我找到了TransparentPanel
班级。但是当我使用那个面板时,我看不到我在代码中输入的图像?
我知道我可以将面板的背景颜色设置为与父级相同。但这在这种情况下不起作用,因为面板位于视频控件的顶部,图像在其下方移动。
所以我需要一个可以显示图像的完全透明的控件。我不确定这是否TransparentPanel
可以使用?
void addpanel()
{
TransparentPanel tp = new TransparentPanel();
//Panel tp = new Panel();
tp.BackColor = Color.Transparent; //This doesn't work?
tp.BackgroundImage = Properties.Resources.arrowup; //This image is a 30% transparent image (opacity 30%)
tp.Size = new System.Drawing.Size(54, 54);
tp.Location = new Point(20, 20);
panel219.Controls.Add(tp);
tp.BringToFront();
}
public class TransparentPanel : Panel
{
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return cp;
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//base.OnPaintBackground(e);
}
}
编辑
我也尝试过这种方法。但是面板中的图像仍然具有几乎是白色的控制颜色的颜色。应该看穿我拥有的图像,因为它是 30% 的不透明度?
void addpanel()
{
TransparentPanel tp = new TransparentPanel(Properties.Resources.arrowup);
tp.BackColor = Color.Transparent; //This doesn't work?
tp.Size = new System.Drawing.Size(54, 54);
tp.Location = new Point(20, 20);
panel219.Controls.Add(tp);
tp.BringToFront();
}
class TransparentPanel : Panel
{
public Image image { get; set; }
public TransparentPanel(Image img)
{
image = img;
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.SupportsTransparentBackColor |
ControlStyles.UserPaint, true);
UpdateStyles();
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
var g = pevent.Graphics;
if (Parent != null)
{
Rectangle rect = new Rectangle(Left, Top, Width, Height);
g.TranslateTransform(-rect.X, -rect.Y);
try
{
using (PaintEventArgs pea =
new PaintEventArgs(g, rect))
{
pea.Graphics.SetClip(rect);
InvokePaintBackground(Parent, pea);
InvokePaint(Parent, pea);
}
}
finally
{
g.TranslateTransform(rect.X, rect.Y);
}
}
if (image != null)
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
var rectSrc = new Rectangle(0, 0, image.Width, image.Height);
var rectDes = new Rectangle(0, 0, Width, Height);
//if (State == MouseState.Over)
rectDes.Inflate(2, 2);
g.DrawImage(image, rectDes, rectSrc, GraphicsUnit.Pixel);
}
}
}