如何计算给定文本在不同屏幕分辨率下以指定宽度占用多少行?
我如何计算给定文本以指定宽度占用多少行? 它适用于不同的屏幕分辨率? 我的代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论