对于我的一个项目,我需要图像显示与透明的背景。我制作了一些具有透明背景的.png图像(为了检查这一点,我在Photoshop中打开了它们)。现在我有了一个扩展PictureBox的类:
class Foo : PictureBox
{
public Foo(int argument)
: base()
{
Console.WriteLine(argument);//different in the real application of course.
//MyProject.Properties.Resources.TRANSPARENCYTEST.MakeTransparent(MyProject.Properties.Resources.TRANSPARENCYTEST.GetPixel(1,1)); //<-- also tried this
this.Image = MyProject.Properties.Resources.TRANSPARENCYTEST;
((Bitmap)this.Image).MakeTransparent(((Bitmap)this.Image).GetPixel(1, 1));
this.SizeMode = PictureBoxSizeMode.StretchImage;
this.BackColor = System.Drawing.Color.Transparent;
}
}
然而,这只是用白色背景显示picturebox,我似乎不能让它在透明背景下工作。
发布于 2012-02-06 18:40:13
如果您想将图像覆盖在图像上(而不是图像覆盖在表单上),这将是一个诀窍:
overImage.Parent = backImage;
overImage.BackColor = Color.Transparent;
overImage.Location = thePointRelativeToTheBackImage;
其中overImage和backImage是带有png的PictureBox (具有透明背景)。
这是因为,如前所述,图像的透明度是使用父容器的背景颜色呈现的。PictureBoxes没有"Parent“属性,所以您必须手动创建它(当然也可以创建一个自定义控件)。
发布于 2012-09-12 17:10:21
CodeProject网站上有一个极好的解决方案,网址为
Making Transparent Controls - No Flickering
本质上,诀窍是重写paintbackground事件,以便循环遍历picturebox底层的所有控件并重新绘制它们。函数为:-
protected override void OnPaintBackground(PaintEventArgs e)
// Paint background with underlying graphics from other controls
{
base.OnPaintBackground(e);
Graphics g = e.Graphics;
if (Parent != null)
{
// Take each control in turn
int index = Parent.Controls.GetChildIndex(this);
for (int i = Parent.Controls.Count - 1; i > index; i--)
{
Control c = Parent.Controls[i];
// Check it's visible and overlaps this control
if (c.Bounds.IntersectsWith(Bounds) && c.Visible)
{
// Load appearance of underlying control and redraw it on this background
Bitmap bmp = new Bitmap(c.Width, c.Height, g);
c.DrawToBitmap(bmp, c.ClientRectangle);
g.TranslateTransform(c.Left - Left, c.Top - Top);
g.DrawImageUnscaled(bmp, Point.Empty);
g.TranslateTransform(Left - c.Left, Top - c.Top);
bmp.Dispose();
}
}
}
}
发布于 2011-04-02 17:44:23
如果您在图片框中显示透明的png,它将自动考虑透明度,因此您不需要设置透明颜色
https://stackoverflow.com/questions/5522337
复制相似问题