你可以试试这段代码。它假设存在一个Panel1
andPictureBox1
在表单上(PictureBox1
在Panel1
with内Panel1.AutoScroll = True
),并且在 上设置了一个图像PictureBox
。
该代码不计算缩放的中心点,但您可以为此使用 e.Location(或 eX/eY)。
更新 - 这是(应该)比以前更健壮的新代码(见底部):
Public Class Form1
Private _originalSize As Size = Nothing
Private _scale As Single = 1
Private _scaleDelta As Single = 0.0005
Private Sub Form_MouseWheel(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel
'if very sensitive mouse, change 0.00005 to something even smaller
_scaleDelta = Math.Sqrt(PictureBox1.Width * PictureBox1.Height) * 0.00005
If e.Delta < 0 Then
_scale -= _scaleDelta
ElseIf e.Delta > 0 Then
_scale += _scaleDelta
End If
If e.Delta <> 0 Then _
PictureBox1.Size = New Size(CInt(Math.Round(_originalSize.Width * _scale)), _
CInt(Math.Round(_originalSize.Height * _scale)))
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
'init this from here or a method depending on your needs
If PictureBox1.Image IsNot Nothing Then
PictureBox1.Size = Panel1.Size
_originalSize = Panel1.Size
End If
End Sub
End Class
旧代码 - 有效,但可能由于 Scale() 中的舍入错误而在大更改时不稳定:
Public Class Form1
Private _scale As New SizeF(1, 1)
Private _scaleDelta As New SizeF(0.01, 0.01) '1% for each wheel tick
Private Sub Form_MouseWheel(sender As System.Object,
e As MouseEventArgs) Handles Me.MouseWheel
'count incrementally
_scale.Height = 1
_scale.Width = 1
If e.Delta < 0 Then
_scale += _scaleDelta
ElseIf e.Delta > 0 Then
_scale -= _scaleDelta
End If
If e.Delta <> 0 Then _
PictureBox1.Scale(_scale)
End Sub
Private Sub Form1_Load(sender As System.Object,
e As EventArgs) Handles MyBase.Load
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
'init picturebox size = image size
If PictureBox1.Image IsNot Nothing Then
PictureBox1.Scale(New SizeF(1, 1))
PictureBox1.Size = PictureBox1.Image.Size
End If
End Sub
End Class