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
 
 
 
 
 
 
TitlePrint a centered picture as large as possible without distortion
KeywordsPictureBox, picture, print, center, aspect ratio
CategoriesGraphics
 
Compare the picture's aspect ratio (height/width) to the printer's aspect ratio. If the picture is relatively tall and thin compared to the printer, make the picture fill the printer vertically. Calculate its printed width to keep its aspect ratio unchanged.

If the picture is relatively short and wide compared to the printer, make the picture fill the printer horizontally. Calculate its printed heihgt to keep its aspect ratio unchanged.

Calculate the X and Y position where the program needs to draw the picture to center it. Then use PaintPicture to draw the picture on the printer.

 
' Print the PictureBox's picture centered and
' draw a box around it.
Private Sub cmdPrint_Click()
Dim picture_aspect As Single
Dim printer_aspect As Single
Dim wid As Single
Dim hgt As Single
Dim X As Single
Dim Y As Single

    ' Set the PictureBox's ScaleMode to pixels to
    ' make things interesting.
    picCanvas.ScaleMode = vbPixels

    ' Compare the picture's and Printer's
    ' aspect ratios.
    picture_aspect = picCanvas.ScaleHeight / _
        picCanvas.ScaleWidth
    printer_aspect = Printer.ScaleHeight / _
        Printer.ScaleWidth
    If pic_aspect > printer_aspect Then
        ' The picture is too tall and thin.
        ' Print it as tall as possible.
        hgt = Printer.ScaleHeight
        wid = hgt / picture_aspect
    Else
        ' The picture is too short and wide.
        ' Print it as wide as possible.
        wid = Printer.ScaleWidth
        hgt = wid * picture_aspect
    End If

    ' See where we need to place the picture
    ' to center it.
    X = Printer.ScaleLeft + (Printer.ScaleWidth - wid) / 2
    Y = Printer.ScaleTop + (Printer.ScaleHeight - hgt) / 2

    ' Print the picture.
    Printer.PaintPicture picCanvas.Picture, X, Y, wid, hgt

    ' Draw the box.
    Printer.Line (X, Y)-Step(wid, hgt), , B

    ' Finish printing.
    Printer.EndDoc

    MsgBox "Done"
End Sub
 
For more information on printing and graphics in Visual Basic, see my book Visual Basic Graphics Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated