13

How would I go about rotating a Bitmap in Windows GDI,C++?

MxNx
  • 1,240
  • 17
  • 26
H4cKL0rD
  • 5,193
  • 15
  • 50
  • 73

3 Answers3

9

You can do it with GDI+ (#include <gdiplus.h>). The Graphics class has the RotateTransform method. That allows arbitrary rotations. Use Image::RotateFlip() if you only need to rotate by 90 degree increments, that's a lot more efficient.

Hans Passant
  • 897,808
  • 140
  • 1,634
  • 2,455
  • 5
    @Frank Krueger - you have to be able to mind-read on this site. Either that, or throw pasta at the wall and see what sticks. – Mark Ransom Feb 16 '10 at 05:05
  • 1
    Better stick with raw GDI+ implementation as RotateFlip is infamous for throwing out the 'Generic GDI+ error occured' exception quite often. – Ε Г И І И О May 02 '13 at 10:49
5

Sounds like you have to use PlgBlt. Take your rectangle's 4 corners as 2D Points, rotate them, then call PlgBlt.

From MSDN Bitmap Rotation:

To copy a bitmap into a parallelogram; use the PlgBlt function, which performs a bit-block transfer from a rectangle in a source device context into a parallelogram in a destination device context. To rotate the bitmap, an application must provide the coordinates, in world units, to be used for the corners of the parallelogram.

Frank Krueger
  • 67,384
  • 46
  • 159
  • 207
  • 2
    The PlgBlt docs specifically mention that rotation transformations are not supported. That's accurate. Link: http://msdn.microsoft.com/en-us/library/dd162804%28VS.85%29.aspx – Hans Passant Feb 16 '10 at 02:48
3

Another possibility (beyond those already suggested) is to use SetWorldTransform(). This is different in that it is modal and applies to the DC as a whole, not just a single operation. If you want to rotate one bitmap rotated, but other things without rotation, it's probably not your best choice. If you want to draw a number of things rotated, or (especially) if you want to rotate everything you draw (at least into one DC) it can work quite nicely though.

Jerry Coffin
  • 455,417
  • 76
  • 598
  • 1,067
  • I tried SetWorldTransform () and it had absolutely no effect. The documentation says that the device context's graphics mode must be set to GM_ADVANCED. I tried it, and it resulted in a totally black bitmap. This is what usually happens when trying a Microsoft feature; it doesn't work, and you spend the other 90% of your time trying to figure out why. .NET is noticeably better, but it's so slow. – user20493 Jul 13 '10 at 19:56