如何在固定尺寸的 PictureBox 中完美显示任意大小的图片

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

作者:牧山道人
原文地址:https://www.seeksunslowly.com/perfect-display-picture-sc
转载请注明出处,谢谢。
_____________________________________

所谓在大小不变的 PictureBox 中完美地显示各种尺寸的图片,应该达到以下要求:
1、PictureBox 位置、大小固定。
2、若图片比 PictureBox 小(或一样大)则居中显示。
3、若图片比 PictureBox 大则以按比例缩放显示。
4、最好给 PictureBox 加上边框。

以下是实现方法(VB 2008):
1、新建 Windows Forms Application。
2、在 Form1 上放置以下控件: PictureBox(Name 设为 pb,Size 设为 260, 174,BorderStyle 设为 FixedSingle)、Button(Name 设为 bBig,Text 设为 Big Picture)、Button(Name 设为 bSmall,Text 设为 Small Picture)。
3、在窗体设计器中双击 Form1 任意位置,将所有代码替换为以下代码:
[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、运行程序,点击<Big Picture>及<Small Picture>按钮即可看到效果(为了方便您观看效果,我在 debug 目录下放置了演示图片)。

源代码下载
https://www.seeksunslowly.com/downloadable-source-codes/perfect-picturebox-display.zip

【赞赏 / Reward】

微信         支付宝         PayPal

Post a comment