Monday, November 7, 2016

Extension PictureBox ResizeImageToFit


Another useful extension, this time for the standard Windows Forms PictureBox. The issue for me, is that I usually just want to throw a picture at it and it should just show it, not crop it, not kill the aspect ratio etc. So I tend to use this extension method after assigning a new picture to the PictureBox.Image property to correctly show the picture in center mode if it is smaller then the box, or zoom it to fit inside the box if it is larger, still keeping the aspect ratio.

Some source-code (C#)
public static void ResizeImageToFit(this PictureBox pbox)
{
 if (pbox.Size.Height > pbox.Image.Size.Height && pbox.Size.Width > pbox.Image.Size.Width)
  pbox.SizeMode = PictureBoxSizeMode.CenterImage;
 else
  pbox.SizeMode = PictureBoxSizeMode.Zoom;
}

Hope this helps someone out there :)

Back to extensions list

Until next time: Work to Live, Don’t Live to Work

No comments:

Post a Comment