在PICTUREBOX上任意角度旋转图形的VB.NET代码
2024-04-01 10:24阅读:
Public Shared Sub RotatePictureBoxImage(pictureBox As
PictureBox, degrees As Single)
'对指定的picturebox中的图像进行旋转
'创建一个新的Bitmap对象,其大小与PictureBox相同
Dim rotatedBitmap As New
Bitmap(pictureBox.Width, pictureBox.Height)
'使用Graphics对象来绘制旋转后的图片
Using graphics As Graphics =
Graphics.FromImage(rotatedBitmap)
'设置高质量插值法以改善图像质量
graphics.InterpolationMode =
Drawing2D.InterpolationMode.HighQualityBicubic
graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
'计算旋转的中心点
Dim centerX As
Single = pictureBox.Width / 2.0F
Dim centerY As
Single = pictureBox.Height / 2.0F
r>
'保存当前的图形状态到堆栈
Dim state As
GraphicsState = graphics.Save()
'将坐标原点移动到图片的中心点
graphics.TranslateTransform(centerX, centerY)
'旋转图形
graphics.RotateTransform(degrees)
'平移图形以使其在旋转后仍然居中
graphics.TranslateTransform(-centerX, -centerY)
'根据PictureBox的SizeMode调整图片大小
Dim sourceRect As
New RectangleF(0, 0, pictureBox.Image.Width,
pictureBox.Image.Height)
Dim destRect As
RectangleF
'根据不同的SizeMode计算目标矩形
Select Case
pictureBox.SizeMode
Case PictureBoxSizeMode.Normal
'在Normal模式下,图片大小不变,可能需要进行裁剪或留白
destRect = sourceRect
Case PictureBoxSizeMode.AutoSize
'AutoSize模式下,PictureBox会根据图片大小自动调整,这里不处理
'通常不会在保持PictureBox大小不变的情况下旋转图片
MsgBox('无法旋转设置为AutoSize模式的图片。')
Case PictureBoxSizeMode.StretchImage
'拉伸图片以填充PictureBox
destRect = New RectangleF(0, 0, pictureBox.Width,
pictureBox.Height)
Case PictureBoxSizeMode.Zoom
'保持图片的纵横比并缩放以适应PictureBox
Dim scaleWidth As Single = pictureBox.Width /
sourceRect.Width
Dim scaleHeight As Single = pictureBox.Height /
sourceRect.Height
Dim scale As Single = Math.Min(scaleWidth,
scaleHeight)
'计算缩放后的图片大小和位置,使其居中
destRect = New RectangleF(
(pictureBox.Width -
(sourceRect.Width * scale)) / 2,
(pictureBox.Height -
(sourceRect.Height * scale)) / 2,
sourceRect.Width * scale,
sourceRect.Height * scale)
Case Else
'其他情况可以按需处理或抛出异常,我这里不展开。
Throw New NotImplementedException('不支持的PictureBox
SizeMode')
End Select
'绘制旋转后的图片到新的Bitmap中
graphics.DrawImage(pictureBox.Image, destRect, sourceRect,
GraphicsUnit.Pixel)
'恢复原始的图形状态
graphics.Restore(state)
End Using
'将旋转后的图片设置回PictureBox
pictureBox.Image =
rotatedBitmap
End Sub