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
 
 
 
 
 
TitleCenter an image, shrinking it to fit if necessary
Keywordscenter image, image, bitmap, picture, shrink, PaintPicture
CategoriesGraphics
 
Shrink the image if it will not fit, maintaining the aspect ratio. Use PaintPicture to copy it into the correct position to center it.

 
' Center the image.
Private Sub Form_Resize()
Dim to_x As Single
Dim to_y As Single
Dim wid As Single
Dim hgt As Single

    If picHidden.Picture = 0 Then Exit Sub
    
    Cls
    
    ' See if the image is too big to fit.
    wid = picHidden.ScaleWidth
    hgt = picHidden.ScaleHeight
    If wid > ScaleWidth Then
        hgt = hgt * ScaleWidth / wid
        wid = ScaleWidth
    End If
    If hgt > ScaleHeight Then
        wid = wid * ScaleHeight / hgt
        hgt = ScaleHeight
    End If

    ' See where we need to put the picture to center it.
    to_x = (ScaleWidth - wid) / 2
    to_y = (ScaleHeight - hgt) / 2

    ' Copy the picture centered on the form.
    Me.PaintPicture picHidden.Picture, _
        to_x, to_y, wid, hgt
End Sub
 
For lots of other graphics techniques, see my book Visual Basic Graphics Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated