Search code examples
c#graphicsgdi+bitmapdata

Is there a way to create Graphics from BitmapData?


I'm using BitmapData to perform various drawing on it. Now i'm looking to draw some text.
Because i would like to avoid the complexity of implementing the string fonts to pixels transformation I would like to use the available DrawString method on graphics object.

So I'm looking for a way to create a Graphic object working on a device that will be my BitmapData.

I saw there is a Graphics.FromHdc method available. But when i use it with the Scan0 of my BitmapData it throws a System.OutOfMemoryException.


Solution

  • Usually a BitmapData object is derived from an existing Bitmap like this:

    Bitmap bmp = // insert some way to create your bitmap!
    Rectangle rect = new Rectangle(Point.Empty, bmp.Size);
    
    BitmapData BD =  bmp.LockBits(rect , ImageLockMode.ReadWrite,  bmp.PixelFormat);
    //  
    //  do your pixel stuff here
    //
    bmp.UnlockBits(BD);
    
    using (Graphics G = Graphics.FromImage(bmp) )
    {
        //
        // do your Graphics stuff here
        // 
    }