Graphics.RotateTransform() does not rotate my picture

冷暖自知 提交于 2019-12-12 03:49:00

问题


I have problem with Graphics.RotateTransfrom() with the following code :

    Dim newimage As Bitmap
    newimage = System.Drawing.Image.FromFile("C:\z.jpg")
    Dim gr As Graphics = Graphics.FromImage(newimage)
    Dim myFontLabels As New Font("Arial", 10)
    Dim myBrushLabels As New SolidBrush(Color.Black)
    Dim a As String

    '# last 2 number are X and Y coords.
    gr.DrawString(MaskedTextBox2.Text * 1000 + 250, myFontLabels, myBrushLabels, 1146, 240) 
    gr.DrawString(MaskedTextBox2.Text * 1000, myFontLabels, myBrushLabels, 1146, 290)
    a = Replace(Label26.Text, "[ mm ]", "")

    gr.DrawString(a, myFontLabels, myBrushLabels, 620, 1509)
    a = Replace(Label5.Text, "[ mm ]", "")

    gr.DrawString(a, myFontLabels, myBrushLabels, 624, 548)

    gr.RotateTransform(90.0F)

    gr.DrawString(a, myFontLabels, myBrushLabels, 0, 0)

    PictureBox1.Image = newimage

I dont know why but my image in pictureBox1 is not rotated. Someone known solution ?


回答1:


The issue at hand is that the RotateTransform method does not apply to the existing image.

Instead, it applies to the transformation matrix of the graphics object. Basically, the transformation matrix modifies the coordinate system used to add new items.

Try the following :

    Dim gfx = Graphics.FromImage(PictureBox1.Image)

    gfx.DrawString("Test", Me.Font, Brushes.Red, New PointF(10, 10))
    gfx.RotateTransform(45)
    gfx.DrawString("Rotate", Me.Font, Brushes.Red, New PointF(10, 10))

The first string is drawn normally, while the second is drawn rotated.

So what you need to do is create a new graphics object, apply your rotation, draw your source image onto the graphics (graphics.DrawImage), and then draw all your text :

    ' Easy way to create a graphisc object
    Dim gfx = Graphics.FromImage(PictureBox1.Image)

    gfx.Clear(Color.Black)
    gfx.RotateTransform(90) ' Rotate by 90°

    gfx.DrawImage(Image.FromFile("whatever.jpg"), New PointF(0, 0))
    gfx.DrawString("Test", Me.Font, Brushes.Red, New PointF(10, 10))
    gfx.DrawString("Rotate", Me.Font, Brushes.Red, New PointF(10, 10))

But beware of rotation, you'll find that you need to change the coordinates at which you draw your image (Or change the RenderingOrigin property of the graphics, setting it to the center of the image makes it easier to handle rotations), otherwise your picture won't be visible (it will be drawn, but off the visible part of the graphics).

Hope that helps



来源:https://stackoverflow.com/questions/13579409/graphics-rotatetransform-does-not-rotate-my-picture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!