Using Windows forms, I have a rectangle in which I want to paint some text inside using Graphics.DrawString
. What I want to do though, is create the font as large as possible, whilst keeping the text within the bounds of the rectangle and only wrapping text to the next line between words.
e.g.
Not acceptable Acceptab开发者_开发知识库le
+-------+ +--------+
| dotne | | |
| t | | dotnet |
| rocks | | rocks |
+-------+ +--------+
in semi-pseudo code, this is what I'm thinking of
string text = "This is some Text";
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
RectangleF rect = new RectangleF(0,0,100,100);
float maxFontSize = 10F;
float minFontSize = 6F;
float fontSize = maxFontSize;
Font font = new Font(fontFamily, fontSize);
bool found = false;
do
{
font = new Font(fontFamily, fontSize);
if TextFitsWithinBounds(text, font, rect, sf)
found = true;
else
fontSize -= 0.1F;
} while (found == false && fontSize > minFontSize)
Graphics.DrawString(text, font, Brushes.Black, rect, sf);
What I'm looking for is a means of implementing TextFitsWithinBounds(). Is there a class anywhere in the framework that will help me achieve this?
MeasureString comes close, but that doesn't appear to allow me to specify the bounds.
The graphics object has a .MeasureString()
member, resulting in the size of the drawn text.
精彩评论