C#Picturebox透明背景似乎不起作用

teu*_*oon 18 c# transparency picturebox

对于我的项目,我需要使用透明背景显示图像.我制作了一些具有透明背景的.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,这只是显示带有白色背景的图片框,我似乎无法使其与透明背景一起工作.

Tob*_*bon 38

如果你想在图像上叠加图像(而不是在图像上叠加图像),这就可以了:

overImage.Parent = backImage;
overImage.BackColor = Color.Transparent;
overImage.Location = thePointRelativeToTheBackImage;
Run Code Online (Sandbox Code Playgroud)

其中overImage和backImage是带有png的PictureBox(具有透明背景).

这是因为,如前所述,使用父容器的背景颜色渲染图像的透明度.PictureBoxes没有"Parent"属性,所以你必须手动(或者当然创建一个cutom控件).


Han*_*ant 20

它可能完美无缺.您正在看到图片框控件背后的内容.哪种形式.谁的BackColor可能是白色的.您可以设置表单的BackgroundImage属性以确保,您应该通过图片框看到图像.像这样:

在此输入图像描述

通过冲孔的孔图片框形式需要一个更大的武器,Form.TransparencyKey

  • 这不是真正的透明度.如果图片框后面有另一个控件,则不会透过透明区域显示.相反,表单背景将显示在控件上. (2认同)

小智 12

CodeProject网站上有一个很好的解决方案

制作透明控制 - 无闪烁

本质上的技巧是覆盖paintbackground事件,以便遍历图片框底层的所有控件并重绘它们.功能是: -

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();
               }
           }
       }
   }
Run Code Online (Sandbox Code Playgroud)

  • 今天仍然相关,这篇文章...迫不及待地想从老板那里切换到wpf :( (2认同)