开发者

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 s开发者_如何学Cize. It seems like a circular paradox!

Someone please help me out on this?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜