winform 动态截断或者补全文字宽度

使用 TabControl 时,发现它的选项卡宽度会随文字长度变化,我自己做了一个浏览器,发现很难看,于是写了个算法,对文字长度进行填充或截断,效果很不错:

 

调用代码:
using (var g = tabs.CreateGraphics())
{
    tabPage.Text = "  " + PadAndEllipsis(g, tabs.Font, title, 150) + "  " ;
}

核心函数:

复制代码
/// <summary>
/// 长度不够用空格前后填充,长度超过则截断并添加...
/// </summary>
/// <param name="g"></param>
/// <param name="font"></param>
/// <param name="str"></param>
/// <param name="maxWith"></param>
/// <returns></returns>
string PadAndEllipsis(Graphics g, Font font, string str, int maxWith)
{
    Func<string, float> getActualWidth = delegate (string text)
    {
        return g.MeasureString("|" + text + "|", font).Width - g.MeasureString("||", font).Width;
    };

    var originalWidth = getActualWidth(str);
    var expectedStr = str;

    //字符串增加空格使它突破宽度
    if (originalWidth < maxWith)
    {
        const string fillstr = " ";

        //快速填充使其超过标准宽度
        do
        {
            expectedStr = expectedStr + string.Concat(Enumerable.Repeat(fillstr, expectedStr.Length));
        } while (getActualWidth(expectedStr) < maxWith);

        //使用二分查找法
        var start = 0;
        var end = expectedStr.Length;
        while (start < end)
        {
            var pos = start + (int)Math.Ceiling(((double)end - start) / 2);
            if (getActualWidth(expectedStr.Substring(0, pos)) > maxWith)
            {
                if (end == pos)
                    break;
                end = pos;
            }
            else
            {
                if (start == pos)
                    break;
                start = pos;
            }
        }

        var padding = string.Concat(Enumerable.Repeat(fillstr, (end - str.Length) / 2));
        var result = padding + str + padding;
        var w = getActualWidth(result);
        return result;
    }
    else
    {
        const string suffixstr = "...";

        //使用二分查找法
        var start = 0;
        var end = expectedStr.Length;
        while (start < end)
        {
            var pos = start + (int)Math.Ceiling(((double)end - start) / 2);
            if (getActualWidth(expectedStr.Substring(0, pos) + suffixstr) > maxWith)
            {
                if (end == pos)
                    break;
                end = pos;
            }
            else
            {
                if (start == pos)
                    break;
                start = pos;
            }
        }

        var result = str.Substring(0, start) + suffixstr;
        return result;
    }
}
复制代码

 

posted on   空明流光  阅读(24)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-07-16 centos 7.5 设置自定义程序 开机自启

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示