Sizing a bitmap to store a text string

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

The problem is, how can I know in advance, when I create my initial bitmap, how many pixels are wide and longer for my bitmap?

I know this has something to do with MeasureString (), but to use MeasureString () I need to get the Graphics object from the bitmap. I cannot get this until I create a bitmap, which I cannot do until I know the size. This is like a circular paradox!

Can someone please help me with this?

+5
source share
2 answers

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);
}

Image size does not affect measurement

+6
source

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

We hope that the size of the graphic element will not affect the result of MeasureString.

0
source

All Articles