Search code examples
c#winformsgraphicsbitmapdrawstring

Determining bitmap size to hold text string


What I am trying to do is use the DrawString() method to draw a string to a bitmap. To do this, I need to create a bitmap and get a Graphics object from the bitmap, then call DrawString() on that Graphics object.

The problem is, how do I know, in advance, when I create my initial bitmap, how many pixels wide and long to make my bitmap?

I know this has something to do with MeasureString(), but in order to use MeasureString(), I need to get the Graphics object from the bitmap. I can't get that till I create the bitmap, which I can't do till I know the size. It seems like a circular paradox!

Someone please help me out on this?


Solution

  • You can create a small static Bitmap to measure on

    private static Bitmap measureBmp = new Bitmap(1, 1);
    

    Then you measure as usual

    using (var measureGraphics = Graphics.FromImage(measureBmp))
    {
        var stringSize = measureGraphics.MeasureString("measureString", this.Font);
    }
    

    The size of the image does not affect the measurement