获取以像素为单位的字符大小 [英] Get character size in pixel

查看:89
本文介绍了获取以像素为单位的字符大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得一个字符的像素大小?

像C#中的此命令一样

Hi, how I can get the size in pixel of one character?

Like this command in C#

Font font = getGraphics().getFont();

int textWidth = font.stringWidth("Comprimento em pixels desta string!");

int fontHeight = font.getHeight();



但是,我想知道如何使用WinApi在C中做到这一点.
谢谢



But, i want to know, how I can do this in C, using WinApi.
Thanks

推荐答案

看看:
GDI +扁平API文本函数 [ ^ ].

最好的问候
Espen Harlinn
Have a look at:
GDI+ Flat API Text Functions[^].

Best regards
Espen Harlinn


HDC		hDC;		// handle to device context
TEXTMETRIC	textMetric;	// text metric information
HFONT		hFont, hOldFont;

hDC = GetDC(hWnd);
// get a 10-point font and select it into the DC
int points = MulDiv(10, GetDeviceCaps(hDC, LOGPIXELSY), 72);
hFont = CreateFont(-points, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, L"Courier New");
hOldFont = SelectFont(hDC, hFont);

GetTextMetrics(hDC, &textMetric);

int currentY = textMetric.tmHeight; // character height in current font



[edit]
您还应该检查所有字体和文本功能 [ ^ ],以获取更多信息.
[/edit]



[edit]
You should also check all the Font and Text functions[^], for further information.
[/edit]


除了Richard和Espen提供的解决方案外,您还可以使用DT_CALCRECT作为文本绘制标记,通过调用DrawText来实现此目的.
对于单行文本,只需在使用前将rect成员设置为0.
对于多行文本,将"right"成员设置为所需的宽度.

In addition to the solutions provided by Richard and Espen, you can achieve this using a call to DrawText, using DT_CALCRECT as the text-drawing flag.

For single line text, just set the rect members to 0 before use.
For multi-line text, set the ''right'' member to the desired width.

HDC hDC;
TEXTMETRIC textMetric;
HFONT   hFont, hOldFont;
int sizeInPpoints, lineHeight;
RECT textRect;
char *buffer = "Comprimento em pixels desta string!";

hDC = GetDC(hwnd);
sizeInPpoints = MulDiv(10, GetDeviceCaps(hDC, LOGPIXELSY), 72);
hFont = CreateFont(-sizeInPpoints, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, "Courier New");
hOldFont = (HFONT)SelectObject(hDC, hFont);

GetTextMetrics(hDC, &textMetric);

lineHeight = textMetric.tmHeight; // character height in current font

textRect.left = textRect.right = textRect.top = textRect.bottom = 0;
DrawText(hDC, buffer, strlen(buffer), &textRect, DT_CALCRECT);

printf("Size of text calculated by DrawText: [%d x %d]\n", textRect.right, textRect.bottom);
printf("Height of text calculated by GetTextMetrics: %d\n", lineHeight);



输出:



Output:

Size of text calculated by DrawText: [280 x 16]
Height of text calculated by GetTextMetrics: 16


这篇关于获取以像素为单位的字符大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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