質問

I've been asked to generate placeholder graphics for some items in a database but with one caveat - the font size needs to be dynamic so that the text fills the entire graphic.

The first iteration of the code works just fine, but the client wants to the font to be bigger so that the graphics are easier to read. Here's a snippet of the part which generates the text:

using (Graphics Graphic = Graphics.FromImage(Img))
{
   // Add Some Padding
   Width = Width - 20;
   Height = Height - 20;

   // Generate The Text
   Font GraphicFont = new Font("Arial", 26, FontStyle.Bold);
   RectangleF RectF = new RectangleF(10, 10, (float)Width, (float)Height);
   StringFormat sf = new StringFormat();
   sf.Alignment = StringAlignment.Near;
   sf.LineAlignment = StringAlignment.Near;
   Graphic.DrawString(Title, GraphicFont, Brushes.Black, RectF, sf);
}

Is there I can detect text overflow in my RectangleF, or can I detect the size of my DrawString before I apply it to the graphic, or is there some other magic I can do to get the text to fill the graphic?

I would like the text to wordwrap and the font to be the same size for all the words, so it doesn't necessarily need to fill the graphic entirely - hope this all makes sense.

役に立ちましたか?

解決

Use Graphics.MeasureString (documentation: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx)

If you want to size text to fill a region, you can do binary search on different sizes to determine the largest size that still fits in your target region, then use that size to actually draw the string.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top