views:

502

answers:

3

How do I draw a bitmap to a DC, while rotating it by a specified angle?

+2  A: 

I'm not sure that this is the best way of doing it, but one option would be to convert it to a wx.Image with ConvertToImage (wxWidgets help) and then use the rotate function (wxWidgets help). You could then (if necessary) convert it back with ConvertToBitmap (wxWidgets help).

I couldn't see an obvious function that could be used to apply a coordinate transform to the drawing context (DC), but there may be one in there somewhere...

Hope that helps.

Al
+1  A: 

I agree with Al - he deserves the answer, but this (admittedly untested) code fragment should do what you asked for:

def write_bmp_to_dc_rotated( dc, bitmap, angle ):
    '''
    Rotate a bitmap and write it to the supplied device context.
    '''
    img = bitmap.ConvertToImage()
    img_centre = wx.Point( img.GetWidth()/2, img.GetHeight()/2 )
    img = img.Rotate( angle, img_centre )
    dc.WriteBitmap( img.ConvertToBitmap(), 0, 0 )

One thing to note though from the docs:

...using wxImage is the preferred way to load images in wxWidgets, with the exception of resources...

Was there a particular reason to load it as a bitmap rather than a wx.Image?

Jon Cage
I need to draw it to the screen, and the wx.Image doc says I'll need to convert it to bitmap before I could draw it.
cool-RR
After a bit of fixing, your code worked.
cool-RR
Can you either post the fixed result yourself or suggest what you did to fix the above to improve the example?
Jon Cage
I ended up doing it with a GraphicsContext, similar to what Anurag suggested.
cool-RR
A: 

i think better way if you want a generic rotation e.g. rorate bitmap or text or any other drawing path use Graphics context

gc = wx.GCDC(dc)
gc.Rotate(angle)
gc.DrawText("anurag", 100, 100)
Anurag Uniyal
It sounded promising, but GCDC doesn't seem to have a `Rotate` method!
cool-RR
which version and platform you are using?wxPython doc says it does have Rotateand I do use it heavilyhttp://www.wxpython.org/docs/api/wx.GraphicsContext-class.html#Rotate
Anurag Uniyal
I'm confused. Check this out: http://www.wxpython.org/docs/api/wx.GCDC-class.htmlWhat's the connection between GraphicsContext and GCDC?
cool-RR