7

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?

dtb
  • 213,145
  • 36
  • 401
  • 431
Icemanind
  • 47,519
  • 50
  • 171
  • 296

2 Answers2

8

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

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
  • Yeah, but you created a 1x1 bitmap. My bitmap is obviously going to need to be bigger than that. – Icemanind Nov 30 '10 at 20:18
  • 2
    icemanind: The 1x1 bitmap is just for measurement. Once you get `stringSize`, you can create the proper size bitmap. – Gabe Nov 30 '10 at 20:22
  • 1
    @icemanind, the size of the bitmap does not affect MeasureString, even if the bitmap is 1x1 this returns `stringSize: {Width = 77.4010315 Height = 13.8251925}` on my computer. – Albin Sunnanbo Nov 30 '10 at 20:24
  • Take care of `StringFormat.GenericTypographic`, [see here](https://stackoverflow.com/questions/1003370/measure-a-string-without-using-a-graphics-object#comment120331713_1003503) and the input and output unit of measure, [see here](https://stackoverflow.com/questions/1003370/measure-a-string-without-using-a-graphics-object#comment120331866_1003503). – Andre Kampling Jun 22 '21 at 11:59
0

I had to do this in Java, in which I created an unattached graphics element to get access to the structure I needed. You may be able to get away with creating a 1x1 bitmap just to get access to the Graphics object. Then, let it be collected.

The hope here is that the dimensions of the graphics element won't impact the result of MeasureString.

Tim Reynolds
  • 734
  • 3
  • 9
  • 17