BCB:如何获得给定TFont中角色的(近似)宽度?

Maw*_*awg 1 c++builder

这是一个TMemo,而不是那应该有所不同.

谷歌搜索表明我可以使用,Canvas->TextWidth()但这些是德尔福的例子,BCB似乎没有提供这个属性.

我真的想要类似于memo->Font->Height宽度的东西.

我意识到并非所有字体都是固定宽度,因此可以做出很好的估计.

我需要的只是以像素为单位获取TMemo的宽度,并合理猜测它将保存当前字体的字符数.


当然,如果我真的想要懒惰,我可以谷歌的平均身高/宽度比,因为身高已知.请记住,对于我来说,近似值对我来说已经足够好了.

http://www.plainlanguagenetwork.org/type/utbo211.htm说:"对于大多数应用,建议宽高比为3:5(0.6)"

Tom*_*sen 5

实际上你的谷歌搜索并没有完全关闭.您确实需要访问画布对象,或者至少需要访问DC对象的句柄.通常,当搜索有关VCL类的帮助时,搜索delphi示例通常是值得的,因为这些更常见.

无论如何要计算字符串的大小,你可以查看TextExtent函数,它是TCanvas类的函数.只需传递要测试的宽度字符,返回值将是一个TSize构造.然而,还有一个TextWidth功能,以及一个TextHeight功能.你也可以使用它们.实际上这些TextExtent内部呼唤.

你必须注意一件事,函数使用TCanvas对象的当前字体,更具体地说是绑定到画布使用的DC的字体.因此,首先指定要测试的字体,然后传递该字符.

我有一些旧的代码来计算字符串的宽度,如下所示:

// This canvas could be the form canvas: canvas = Form1->Canvas or the 
// memo canvas which will probably be what you want.
canvas->Font->Assign(fontToTest);
int textwidth = TextWidth(textToTest);
Run Code Online (Sandbox Code Playgroud)

如果您想要更多地控制要执行的操作,您也可以使用Windows API执行此操作,这基本上是VCL为您执行的操作,在这种情况下,以下示例如下所示:

// This canvas could be the form canvas: canvas = Form1->Canvas
canvas->Font->Assign(fontToTest);
// The initial size, this is really important if we use wordwrapping. This is 
// the text area of the memo control.
TRect rect = ClientRect; 
// This is the font format we wish to calculate using, in this example our text
// will be left aligned, at the top of the rectangle.
fontformat = DT_LEFT | DT_TOP;
// Here we calculate the size of the text, both width and height are calculated
// and stored in the rect variable. Also note that we add the DT_CALCRECT to the
// fontformat variable, this makes DrawTextEx calculate the size of the text,
// without drawing it.
::DrawTextEx(canvas->handle, 
            textToTest.c_str(), 
            textToTest.Length(), 
            &rect, 
            fontformat | DT_CALCRECT, 
            NULL);
// The width is:
int width = rect.Width();
Run Code Online (Sandbox Code Playgroud)

fontformat是一个参数,它指定了如何对齐和布局文本的不同选项,如果您计划绘制文本,最好查看它提供的不同可能性:DrawTextEx函数[1]

编辑:再次阅读您的问题,让我感到震惊的是您可能正在搜索的功能是:GetTextExtentExPointWindows API文档说明了以下有关此功能的内容:

所述GetTextExtentExPoint函数检索在指定的字符串中的字符,将适合特定空间内的数,并填充有用于每个这些字符的文本程度的阵列.(文本范围是空格开头与适合空格的字符之间的距离.)此信息对于自动换行计算很有用.

您可以在GetTextExtentExPoint此处找到有关此函数的更多信息:GetTextExtentExPoint函数[2]

[1] http://msdn.microsoft.com/en-us/library/dd162499%28VS.85%29.aspx
[2] http://msdn.microsoft.com/en-us/library/dd144935%28VS 0.85%29.aspx