Windows 窗体动态调整文本大小以适合矩形
使用 Windows 表单,我有一个 矩形 我想在其中绘制使用 Graphics.DrawString 里面的一些文本。不过,我想做的是创建尽可能大的字体,同时将文本保持在矩形的边界内,并且仅将文本换行到单词之间的下一行。
例如
Not acceptable Acceptable
+-------+ +--------+
| dotne | | |
| t | | dotnet |
| rocks | | rocks |
+-------+ +--------+
,在半伪代码中,这就是我正在思考的
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);
我正在寻找的是实现 TextFitsWithinBounds() 的方法。框架中是否有一个类可以帮助我实现这一目标?
MeasureString 很接近,但这似乎不允许我指定界限。
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 Acceptable
+-------+ +--------+
| 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
图形对象有一个
.MeasureString()
成员,用于得出绘制文本的大小。The graphics object has a
.MeasureString()
member, resulting in the size of the drawn text.