.net/vb.net图片绕中心旋转任意角

效果图:

弧度制转换:rad= angle * Math.PI / 180

题外话:我之前一直拿着角度制传入三角函数结果大翻车,因为sin cos tan等三角函数都要传入弧度制

先计算旋转后的rectangle

    ''' <summary>
    ''' 计算矩形在旋转任意角之后的区间
    ''' </summary>
    ''' <param name="width">原图片的宽度</param>
    ''' <param name="height">原图片的高度</param>
    ''' <param name="angle">顺时针旋转的较多</param>
    ''' <returns>旋转后的区间</returns>
    Public Function GetRotateRect(width As Integer, height As Integer, angle As Integer) As Rectangle
        Dim rad = angle * Math.PI / 180
        Dim cos As Double = Math.Cos(rad)
        Dim sin As Double = Math.Sin(rad)
        Dim newWidth As Integer = CInt(Math.Max(Math.Abs(width * cos - height * sin), Math.Abs(width * cos + height * sin)))
        Dim newHeight As Integer = CInt(Math.Max(Math.Abs(width * sin - height * cos), Math.Abs(width * sin + height * cos)))
        Return New Rectangle(0, 0, newWidth, newHeight)
    End Function

计算完之后就要画图了,由于我们要的是这种效果,所以就要从中间开始画

''' <summary>
''' 输出原图中心旋转后的图片
''' </summary>
''' <param name="bmp">原图</param>
''' <param name="angle">旋转角度</param>
''' <returns>返回旋转后的图片</returns>
Public Function DrawRatateRect(bmp As Bitmap, angle As Integer) As Bitmap
    Dim w As Integer = bmp.Width
    Dim h As Integer = bmp.Height
    Dim RotateRect As Rectangle = GetRotateRect(w, h, angle)
    Dim RW As Integer = RotateRect.Width
    Dim RH As Integer = RotateRect.Height
    Dim Dest As New Bitmap(RW, RH)
    Dim g As Graphics = Graphics.FromImage(Dest)
    Dim CenterPoint As New Point(RW / 2, RH / 2)
    g.TranslateTransform(CenterPoint.X, CenterPoint.Y)
    g.RotateTransform(angle)
    g.TranslateTransform(-CenterPoint.X, -CenterPoint.Y)

    Dim offset As New Point((RW - w) / 2, (RH - h) / 2)
    g.DrawImage(bmp, New Rectangle(offset, New Size(w, h)))
    g.ResetTransform()
    g.Save()
    Return Dest
End Function

效果很好!

主窗体调用:

DrawRatateRect(New Bitmap("C:\Users\Abfun\Desktop\tmp.png"), 20).Save("C:\Users\Abfun\Desktop\tmp2.png")

猜你喜欢

转载自blog.csdn.net/weixin_56050945/article/details/128745838
今日推荐