没有 CDC 的 MFC 字符串宽度
有没有办法在不使用 CDC 或使用未与显示器链接的 CDC 的情况下获取字符串的宽度(以像素为单位)。需要检索字符串宽度的类不是从 CWnd 继承才能使用 CWnd::GetDC(),并且无法将现有的 CDC 传递给该函数。
我尝试创建一个未与显示器链接的虚拟 CDC,但这会导致 MFC 崩溃。理想情况下,类似于:
m_font = new CFont();
m_font->CreatePointFont(size * 10, _T("Arial"));
m_tempCDC = new CDC();
m_tempCDC->SelectObject(m_font);
return m_tempCDC->GetOutputTextExtent(_T("Test")).cx;
编辑:应该用字体名称变量替换字符串文字。
Is there any way to get the width of a string in pixels without using CDC or using a CDC not linked with a display. The class that needs to retrieve the string width does not inherit from CWnd in order to use CWnd::GetDC() and there is no way to pass an existing CDC to the function.
I have tried to create a dummy CDC that is not linked with a display, however this causes MFC to crash. Ideally something like:
m_font = new CFont();
m_font->CreatePointFont(size * 10, _T("Arial"));
m_tempCDC = new CDC();
m_tempCDC->SelectObject(m_font);
return m_tempCDC->GetOutputTextExtent(_T("Test")).cx;
EDIT: Should have substituted the font name variable for a string literal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字体的宽度取决于它如何转换为像素,并且这取决于渲染它的设备。例如,打印机与显示器显然是不同的。这就是为什么您需要 DC 来实现此功能。
您可以使用 CDC::FromHandle(::GetDC(NULL)) 获取桌面的 DC。
The width of a font is dependent on how it is converted to pixels, and this is dependent on the device it is being rendered on. It will obviously be different for a printer versus a monitor for example. This is why you need a DC for this function.
You can get the DC for the desktop using
CDC::FromHandle(::GetDC(NULL))
.如果您不知道需要使用的字体,如何计算宽度?
我建议在您看到所需设备上下文的地方计算宽度,并将其传递给您需要此宽度的类。
how can you calculate the width if you do not know the font you need to use?
I would suggest to calculate the width in the place, where you see the device context you need and pass it to the class, where you need this width.