For once and for all: Graphics.DrawImage

During development of the last update of my Offline Maps application I had been struggling with the DrawImage method of the Graphics class in the System.Drawin namespace

All in all it’s not that difficult. You just need to read the documentation very carefully and understand the meaning of the words.

Just to share what I learned, here’s a little tutorial on the method, more specifically the version that accepts two rectangles: DrawImage(Image, Rectangle, Rectangle, GraphicsUnit)

Create the source bitmap:

Bitmap sourceBmp = 
   new Bitmap(113, 113, PixelFormat.Format24bppRgb);
// perform some initalization on the bitmap ...

Which gives us the following:

In this bitmap, we define a source rectangle. The coordinates of the rectangle are relative to the origin of the bitmap:

Rectangle sourceRect = new Rectangle(21, 64, 157, 86);

This results in following rectangle, with respect to the bitmap:

Next, we define a target bitmap and take its graphical device context:

Bitmap target = 
   new Bitmap(118, 97, PixelFormat.Format24bppRgb);
// perform some initalization on the bitmap ...
Graphics gtargetBmp = Graphics.FromImage(target);

We have following empty bitmap (the rectangle is to show its defining rectangle):

And relative to this bitmap (or device context) we define the target rectangle:

Rectangle destinationRect = new Rectangle(-31, -21, 121, 69);

This results in:

And finally we execute our DrawImage method saying:

  1. take this target bitmap (actally its device context) and in it we draw
  2. the Source Bitmap
  3. in the Destination Rectangle (relative to the target bitmap)
  4. using the Source Rectangle (relative to the source bitmap)
gtargetBmp.DrawImage(
   sourceBmp,
   destinationRect,
   sourceRect,
   GraphicsUnit.Pixel);

A visual presentation gives us:

And the final result is:

Voila, hope this helps someone in making sense of this method. As I said, it’s really not that difficult, just got to keep your head with it.

Downloads

Sample code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s