自动调整字体大小以适合矩形 [英] Auto Resize Font to fit rectangle

查看:139
本文介绍了自动调整字体大小以适合矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在.NET 4.5/C#中创建具有自适应大小以适合指定矩形的字体?

How can I create in .NET 4.5 / C# a font with a adaptive size to fit a specified rectangle ?

我有一个基于字符串长度的调整大小,字符串越长,字体大小越小,但是它不能很好地工作,如果字符串太长,则文本会变得非常小.这种方法的问题在于,如果我更改矩形大小,那么所有字体大小都会再次变差.

I have a resize based on the string length, the longer the string, the smaller the fontsize, but it does not work very well, if the string is too long the text gets very small. The problem with this method is that if I change the rectangle size all the font sizes are not good again.

推荐答案

使用图形.MeasureString 您可以测量字符串的大小,从而可以计算出所需的大小.

With Graphics.MeasureString you can measure the size of a string, so you can calculate what you need.

来自MSDN的示例

private void MeasureStringMin(PaintEventArgs e)
{

    // Set up string. 
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);

    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);

    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}

这篇关于自动调整字体大小以适合矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆