Search code examples
c#.netpictureboxsystem.drawing

Override Picturbox OnPaint Event to Rotate the Image -Create Custom Picturebox


I want to create a custom control or override the pictuebox's onpaint event such that i get access to the image before its drawn in the picturbox,so that i can rotate the image.

I know that i can do something like this

private void pictureBox1_Paint(object sender, PaintEventArgs e) {

    e.Graphics.DrawRectangle(Pens.Black, new Rectangle(10, 10, 20, 20));
}

How to get access to the image and how to create a custom control.


Solution

  • Here is a quick example of a subclass: It hides the original Image property and replaces it with one that does a rotation before assigning it:

    class RotatedPictureBox : PictureBox
    {
    
        private Image image;
    
        public new  Image Image {
            get { return image; }  // ?? you may want to undo the rotation here ??
            set {
                  Bitmap bmp = value as Bitmap ;
                  // use the rotation you need!
                  if ( bmp != null )  bmp.RotateFlip(RotateFlipType.Rotate270FlipX);
                  image = bmp;
                  base.Image = Image;
                }
            }
    
    
        }
        public RotatedPictureBox ()
        {
        }
    }
    

    Caveat: Assigning an Image seems to work but I didn't test it for all possible uses.. Known limitations

    • It doesn't rotate images assigned via ImageLocation.
    • I had a crash once, when assigning an image in the Designer, but can't reproduce.