【发布时间】:2019-11-19 19:31:46
【问题描述】:
我有一张在 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);
}
}
}
【问题讨论】:
-
谢谢,我在帖子中尝试了这个:
panel1.BackColor = Color.FromArgb(0, 0, 0, 0);,但结果与:panel1.BackColor = Color.Transparent;相同。面板并没有变得真正透明。无论如何,面板似乎有一个几乎是白色的 CONTROL 背景色 -
设置
ControlStyles.Opaque,控件的背景不会被绘制。你可以在 Paint 事件事件中绘制任何你想要的东西。类似this -
@JQSOFT 不确定你指的是什么。如果您在谈论透明度/半透明,则双缓冲无法与之相处。如果您需要一种缓冲形式,在这种情况下,您可以直接使用BufferedGraphics 类并实现自定义。
-
@JQSOFT 在我链接的示例代码中,您可以看到它已被禁用 (
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);)。使用默认实现,控件将无法正常工作。派生该代码的真正自定义控件使用其自己的 BufferedGraphics 对象。
标签: c# winforms transparent-control