C# Picturebox transparent background doesn't seem to work

前端 未结 6 1707
既然无缘
既然无缘 2020-11-27 06:42

For a project of mine I need images to display with a transparent background. I made some .png images that have a transparent background(to check this I opened them in Photo

6条回答
  •  时光说笑
    2020-11-27 07:20

    There's an excellent solution on the CodeProject website at

    Making Transparent Controls - No Flickering

    essentially the trick is to override the paintbackground event so as to loop through all the controls underlying the picturebox and redraw them. The function is:-

    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();
                   }
               }
           }
       }
    

提交回复
热议问题