Rotating an Image in a picture box

后端 未结 1 1483
庸人自扰
庸人自扰 2020-12-22 13:25

I am currently writing a game which uses an arrow which needs to rotate in order to tell the user at what angle they will \"throw\" their boule. I have coded almost all of t

1条回答
  •  生来不讨喜
    2020-12-22 13:40

    There are several issues with the original code and the VB translation. First, CreateGraphics is almost never the right thing to use. Right after that, it is replaced with one from Graphics.FromImage. This is the right way, since you will be drawing to a bitmap, but neither one is disposed, so the app will leak. This could be a problem if something is rotating on a timer.

    Second, the c# version is flawed: the method expects an offset to be passed but that can be calculated ("How To Use" doest bother to pass an offset). Finally, the c# version is also leaking.

    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
    

    Usage:

    ' 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 
    

    Results (before and after):

    The corners are clipped because your code does not calculate a new bounding rectangle size. If the thing rotating is inside a larger image, it could still work.


    Using the Rotate method to redirect an arrow back and forth -90 to 90 degrees on a timer:

    Smoooth! A lot will depend on the nature of the image to be rotated, and we know nothing about the image in this case. A glance at TaskManager showed nothing leaking - be sure to dispose of the previous image.

    0 讨论(0)
提交回复
热议问题