Search code examples
vb.netwinformspicturebox

rotated image in a picturebox shows rotated and original form


I'm a begginer using VB.Net framework 4.7.2 Winforms. Im trying to rotate an image of a plane in my application , but it shows the rotated one and the original.

Picture

left picture is not rotated and the right is rotated at -25°

    Private Sub Rotation(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        With e.Graphics
            .TranslateTransform(PictureBox1.Width \ 2, PictureBox1.Height \ 2)
            .RotateTransform(dgr)
            .DrawImage(PictureBox1.Image, (-PictureBox1.Width \ 2), (-PictureBox1.Height \ 2))
        End With
    End Sub

This is the code I rotate the image with

I want just the rotated image shown. Thanks in advance.


Solution

  • To elaborate, if you assign an Image object to the Image property of the PictureBox then the control will draw that Image itself every time. If you then draw that same Image object yourself in the Paint event handler then of course you see two images.

    Basically, don't assign anything to the Image property of the control but rather to your own Image field and use that in the Paint event handler:

    Private myImage As Image
    
    Private Sub Rotation(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        With e.Graphics
            .TranslateTransform(PictureBox1.Width \ 2, PictureBox1.Height \ 2)
            .RotateTransform(dgr)
            .DrawImage(myImage, (-PictureBox1.Width \ 2), (-PictureBox1.Height \ 2))
        End With
    End Sub
    

    You would set myImage in code wherever you're currently setting PictureBox1.Image or in the Load event handler if you're currently setting it in the designer.