旋转图片框中的图像

时间:2016-11-04 20:22:58

标签: .net vb.net image

我目前正在编写一款游戏,该游戏使用需要旋转的箭头,以告诉用户他们将“抛出”他们的方块的角度。我已经编码了几乎所有的解决方案,但是我有箭头作为图片框和里面的图像。我需要能够旋转并记录它旋转的角度,我有一个计时器,我打算每次刻度时将图像旋转一度,并在角度变量上加一个。我唯一挣扎的是实际旋转图像。您需要的任何进一步细节,

非常感谢任何帮助, 非常感谢, 丹

Private Function RotateImage(image As Image, angle As Single) As Bitmap
    ' the calling code is responsible for (and must) 
    ' disposing of the bitmap returned

    Dim retBMP As New Bitmap(image)
    retBMP.SetResolution(image.HorizontalResolution, image.VerticalResolution)

    Using g = Graphics.FromImage(retBMP)
        ' rotate aroung the center of the image
        g.TranslateTransform(image.Width \ 2, image.Height \ 2)

        'rotate
        g.RotateTransform(angle)

        g.TranslateTransform(-image.Width \ 2, -image.Height \ 2)

        'draw image to the new boitmap
        g.DrawImage(retBMP, New PointF(0, 0))
    End Using
    Return retBMP
End Function


Private Sub PowerTimer_Tick(sender As Object, e As EventArgs) Handles PowerTimer.Tick

    If ArrowAngle >= 45 Then
        AngleIncreasing = False
    ElseIf ArrowAngle <= -45 Then
        AngleIncreasing = True
    End If
    If AngleIncreasing = True Then
        Arrow.Image = New Bitmap(Arrow.Image)
        Arrow.Image = RotateImage(Arrow.Image, 1)
        Me.Refresh()
        ArrowAngle = ArrowAngle + 1
    Else
        Arrow.Image = RotateImage(Arrow.Image, 1)
        Arrow.Image = RotateImage(Arrow.Image, -1)
        Me.Refresh()
        ArrowAngle = ArrowAngle - 1
    End If
End Sub

1 个答案:

答案 0 :(得分:8)

the original code和VB翻译有几个问题。首先,CreateGraphics几乎不是正确的使用方法。在此之后,它将替换为Graphics.FromImage中的一个。这是正确的方法,因为您将绘制到位图,但没有一个被处理,因此应用程序将泄漏。如果某些东西在计时器上旋转,这可能是个问题。

其次,c#版本存在缺陷:该方法需要传递一个偏移量,但可以计算出来(&#34;如何使用&#34;最不愿意传递偏移量)。最后,c#版本也在泄漏。

Private Function RotateImage(img As Image, angle As Single) As Bitmap
    ' the calling code is responsible for (and must) 
    ' disposing of the bitmap returned

    Dim retBMP As New Bitmap(img.Width, img.Height)
    retBMP.SetResolution(img.HorizontalResolution, img.VerticalResolution)

    Using g = Graphics.FromImage(retBMP)
        ' rotate aroung the center of the image
        g.TranslateTransform(img.Width \ 2, img.Height \ 2)

        'rotate
        g.RotateTransform(angle)

        g.TranslateTransform(-img.Width \ 2, -img.Height \ 2)

        'draw image to the bitmap
        g.DrawImage(img, New PointF(0, 0))

        Return retBMP
    End Using
End Function

用法:

' form level var if rotating over and over
Private CatImg As Bitmap

' elsewhere:
CatImg = New Bitmap("C:\Temp\ceiling_cat.jpg")

' to create a new rotated image:
 Dim bmp = RotateImage(CatImg, -65)
 pb1.Image = bmp

 'ToDo: dispose of the picbox image 

结果(之前和之后):

enter image description here

角落被剪裁,因为您的代码不会计算新的边界矩形大小。如果旋转的东西在较大的图像内,它仍然可以工作。

使用Rotate方法在计时器上前后重定向-90到90度的箭头:

enter image description here

Smoooth!很多将取决于要旋转的图像的性质,在这种情况下我们对图像一无所知。只需看一眼TaskManager就不会泄漏 - 请务必丢弃上一张图片。