Instead of working with Scrollbars in your PictureBox why not just scale the image to fit in the PictureBox. First you'll need to be able to generate new dimensions for your image, to do that create a method that returns a new
Size, like so
csharp
public Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
{
//double to hold the final multiplier to use when scaling the image
double multiplier = 0;
//string for holding layout
string layout;
//determine if it's Portrait or Landscape
if (currH > currW) layout = "portrait";
else layout = "landscape";
switch (layout.ToLower())
{
case "portrait":
//calculate multiplier on heights
if (destH > destW)
{
multiplier = (double)destW / (double)currW;
}
else
{
multiplier = (double)destH / (double)currH;
}
break;
case "landscape":
//calculate multiplier on widths
if (destH > destW)
{
multiplier = (double)destW / (double)currW;
}
else
{
multiplier = (double)destH / (double)currH;
}
break;
}
//return the new image dimensions
return new Size((int)(currW * multiplier), (int)(currH * multiplier));
}
Here you pass it the current height & width and the destination height & width and it returns the proper Size ratio. These are determined by the size of your image (current height & width) and what you want it to be (PictureBox height & width). Then a simple method to do the actual resizing of the image, like this
csharp
private void SetImage()
{
try
{
//create a temp image
Image img = this.pictureBox1.Image;
//calculate the size of the image
Size imgSize = RLM.Image.GenerateImageDimensions(img.Width, img.Height, this.pictureBox1.Width, this.pictureBox1.Height);
//create a new Bitmap with the proper dimensions
Bitmap finalImg = new Bitmap(img, imgSize.Width, imgSize.Height);
//create a new Graphics object from the image
Graphics gfx = Graphics.FromImage(img);
//clean up the image (take care of any image loss from resizing)
gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//empty the PictureBox
this.pictureBox1.Image = null;
//center the new image
this.pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
//set the new image
this.pictureBox1.Image = finalImg;
}
catch (System.Exception e)
{
MessageBox.Show(e.Message);
}
}
This will load your image, with the proper dimensions, into your PictureBox (mine just happens to be named pictureBox1). It also properly scales the image, and cleans it up (the InterpolationMode takes care of this). You will need a reference to the System.Drawing Namespace and the System.Drawing.Drawing2D Namespace.
To use it place this line in either your Form's Load event, or possible the Click event of a Button
csharp
private void Form1_Load(object sender, EventArgs e)
{
SetImage(pictureBox1);
}
And there you have it, a perfectly scaled image to fit within the dimensions of your PictureBox. Hope that helps