How to perfectly display any size images in a fixed size PictureBox

Posted by Admin L in .NET Programming on 18-06-2011. Tags:

Author: Nosa Lee
Original Address: https://www.seeksunslowly.com/perfect-display-picture
To reprint this article, please indicate the source, thank you.
_____________________________________

So-called display any size images in a fixed size PictureBox perfectly, should meet the following requirements:
1. PictureBox’s location and size are fixed.
2. If image’s size is less than PictureBox (or have the same size), display it as centered.
3. If images’ size is greater than PictureBox, display it as scale.
4. It is best to add a border to the PictureBox.

Implementation method(VB 2008):
1. Create a new Windows Forms Application.
2. Put the following controls on Form1: PictureBox (Name = pb, Size = 260, 174, BorderStyle = FixedSingle), Button (Name = bBig, Text = Big Picture), Button (Name = bSmall, Text = Small Picture).
3. Double-click any place on Form1 in the Form Designer, replace all code as following:
[cc lang=”vbnet”]
Public Class Form1
Private _picPath$ = String.Empty
Private Sub bBig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles bBig.Click
‘ Change it to the actual one.
_picPath = Application.StartupPath & “\big.png”
PerfectPBDisplay()
End Sub

Private Sub bSmall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles bSmall.Click
‘ Change it to the actual one.
_picPath = Application.StartupPath & “\small.png”
PerfectPBDisplay()
End Sub

Private Sub PerfectPBDisplay()

Dim img As Image = Image.FromFile(_picPath)
pb.ImageLocation = _picPath

‘ Image size > PictureBox size, display as ‘Zoom’, else display as ‘CenterImage’.
If img.Width > pb.Width Or img.Height > pb.Height Then
pb.SizeMode = PictureBoxSizeMode.Zoom
Else
pb.SizeMode = PictureBoxSizeMode.CenterImage
End If
End Sub
End Class
[/cc]
4. Run this program, just click <Big Picture> and <Small Picture> buttons, you can see the effects instantly (in order to facilitate your viewing, I placed the demo pictures in the debug directory).

Download the source codes
https://www.seeksunslowly.com/downloadable-source-codes/perfect-picturebox-display.zip

【赞赏 / Reward】

微信         支付宝         PayPal

Post a comment