0

I want to move the PictureBox BackgroundImage to get the sprites functionality, so I inherited PictureBox and overrided OnPaintBackground:

    public class PictureBox1 : PictureBox
    {
        int bgX = 0, bgY = 0;

        public void SetImagePos(int X, int Y) {
            bgX = X;
            bgY = Y;
            Invalidate();
            Update();
        }

        protected override void OnPaintBackground(PaintEventArgs e) {
            //base.OnPaintBackground(e);
            e.Graphics.DrawImage(BackgroundImage, -bgX, -bgY, BackgroundImage.Width, BackgroundImage.Height);
        }       
    }

This, however, discards the transparency. the commented //base.OnPaintBackground(e); brings the transparency back, but also with the original image on the background. I also tried e.Graphics.Clear(Color.Transparent), but the background color is still velvet black instead. What am I missing?

I want a simple solution, performance is not an issue.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • There's no true transparency in winforms. It just means the color of the control behind it will be used. – rory.ap Nov 13 '19 at 12:36
  • To allow (faked) transparency you need to __nest__ the controls not just __overlap__. Do you? – TaW Nov 13 '19 at 12:40
  • @TaW you mean to set the BackColor of the underlying Control? So the overlapping is not possible (in a simple way) in WinForms? – Jan Turoň Nov 13 '19 at 12:50
  • 1
    Hard to guess what "original image" might mean, it is PictureBox.Paint() that draws its Image property. PictureBox.OnPaintBackground() draws the Parent to provide the transparency effect, if you see an image back it is probably the form's BackgroundImage. [This post](https://stackoverflow.com/a/9387562/17034) describes how to change the Parent and how to alter the way the designer picks the Parent. The best way to implement sprites is with Graphics.DrawImage(), it automatically layers paint and avoids the (considerable) waste of a control. – Hans Passant Nov 13 '19 at 12:58
  • Nesting control `a` in `b` means `a.Parent=b` or `b.Controls.Add(a)`. Both are the same. Now `b` will shine though any transparent parts of `a`. – TaW Nov 13 '19 at 13:51
  • Do note, that while nesting in a PBox (etc) is simple and will work fine in many situations, most sprites should be able to overlap among themselves, which is bound to fail. So drawing them onto the PBox with DrawImage is the recommended way and will not move more pixels than moving controls.. – TaW Nov 13 '19 at 15:23

0 Answers0