|Title||Print a centered picture as large as possible without distortion|
|Keywords||PictureBox, picture, print, center, aspect ratio|
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 / _
printer_aspect = Printer.ScaleHeight / _
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
' The picture is too short and wide.
' Print it as wide as possible.
wid = Printer.ScaleWidth
hgt = wid * picture_aspect
' 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.
For more information on printing and graphics in Visual Basic, see my book Visual Basic Graphics Programming.