Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFill a PictureBox with a picture preserving its aspect ratio
Keywordspicture, fit, stretch, aspect ratio, resize
CategoriesGraphics
 
Calculate the original picture's aspect ratio (ratio of width to height). Compare that to the aspect ratio of the destination PictureBox.

If the picture is too short and wide compared to the PictureBox, make its width larger so the aspect ratios match.

If the picture is too tall and thin compared to the PictureBox, make its height larger so the aspect ratios match.

Once you know how tall and wide the picture must be, use PaintPicture to copy it with its desired size.

 
' Copy the image from pic_src into pic_dst so it fits and
' has the same aspect ratio as the original picture.
Private Sub FitPictureToBox(ByVal pic_src As PictureBox, _
    pic_dst As PictureBox)
Dim aspect_src As Single
Dim wid As Single
Dim hgt As Single

    ' Get the original picture's aspect ratio.
    aspect_src = pic_src.ScaleWidth / pic_src.ScaleHeight

    ' Get the size available.
    wid = pic_dst.ScaleWidth
    hgt = pic_dst.ScaleHeight

    ' Adjust the wid/hgt ratio to match aspect_src.
    If wid / hgt > aspect_src Then
        ' The area is too short and wide.
        ' Make it narrower.
        wid = aspect_src * hgt
    Else
        ' The area is too tall and thin.
        ' Make it shorter.
        hgt = wid / aspect_src
    End If

    ' Center the image at the correct size.
    pic_dst.Cls
    pic_dst.PaintPicture pic_src.Picture, _
        (pic_dst.ScaleWidth - wid) / 2, _
        (pic_dst.ScaleHeight - hgt) / 2, _
        wid, hgt
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated