如何计算给定文本在不同屏幕分辨率下以指定宽度占用多少行?

发布于 2025-01-20 15:41:01 字数 1172 浏览 4 评论 0原文

我如何计算给定文本以指定宽度占用多少行? 它适用于不同的屏幕分辨率? 我的代码:

int CStrUtils::TextLine(HDC hDC, HFONT hFont, const CString& strText, int nWidht)
{ 
    int nLine = 1;
    int nTextLength = strText.GetLength();
    CString strTextRemain = strText;
    HFONT hOldFont = (HFONT)SelectObject(hDC, (HGDIOBJ)hFont);
    SIZE sizeText = { 0 };
    
    int index = 1;
    while(strTextRemain.IsEmpty() == FALSE)
    {
        if (index > nTextLength)
        {
            break;
        }
        ++index;
        CString strTextTemp = strTextRemain.Left(index);
        GetTextExtentPoint32(hDC, strTextTemp, strTextTemp.GetLength(), &sizeText);
        if (sizeText.cx == nWidht)
        {
            ++nLine;
            strTextRemain = strTextRemain.Right(strTextRemain.GetLength() - index);
            index = 0;
        }
        else if (sizeText.cx > nWidht)
        {
            strTextRemain = strTextRemain.Right(strTextRemain.GetLength() - index + 1);
            index = 0;
            ++nLine;
        }
    }
    (HFONT)SelectObject(hDC, (HGDIOBJ)hOldFont);
    return nLine;
}

它在1920x1080上完美运行,但是在更高的屏幕分辨率(2K或4K)下,计算是错误的,它可以计算一行

How do I calculate how many lines a given text takes up with a specified width?
And it is applicable to different screen resolutions?
My code:

int CStrUtils::TextLine(HDC hDC, HFONT hFont, const CString& strText, int nWidht)
{ 
    int nLine = 1;
    int nTextLength = strText.GetLength();
    CString strTextRemain = strText;
    HFONT hOldFont = (HFONT)SelectObject(hDC, (HGDIOBJ)hFont);
    SIZE sizeText = { 0 };
    
    int index = 1;
    while(strTextRemain.IsEmpty() == FALSE)
    {
        if (index > nTextLength)
        {
            break;
        }
        ++index;
        CString strTextTemp = strTextRemain.Left(index);
        GetTextExtentPoint32(hDC, strTextTemp, strTextTemp.GetLength(), &sizeText);
        if (sizeText.cx == nWidht)
        {
            ++nLine;
            strTextRemain = strTextRemain.Right(strTextRemain.GetLength() - index);
            index = 0;
        }
        else if (sizeText.cx > nWidht)
        {
            strTextRemain = strTextRemain.Right(strTextRemain.GetLength() - index + 1);
            index = 0;
            ++nLine;
        }
    }
    (HFONT)SelectObject(hDC, (HGDIOBJ)hOldFont);
    return nLine;
}

It works perfectly at 1920x1080, but at higher screen resolutions (2k or 4k) the calculation is wrong, it calculates one more line

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文