如何求解一个字符串在打印时的宽度

Rich_Zhou 2000-05-17 03:21:00
已知字体如果得知某字符串在打印时的宽度
...全文
305 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
styx 2000-05-18
  • 打赏
  • 举报
回复
printers.canvas.textwidth......
Lin 2000-05-17
  • 打赏
  • 举报
回复
搞得那么复杂:用Canvas.TextWidth不就可以了么?
江王 2000-05-17
  • 打赏
  • 举报
回复
可以用以下的Windows API:
1.
BOOL GetTextExtentPoint32(
HDC hdc, // handle to device context, 如Canvas.Handle
LPCTSTR lpString, // pointer to text string, 如PChar( str )
int cbString, // number of characters in string, 如Length( str )
LPSIZE lpSize // pointer to structure for string size
);
该函数是用来获得一字符串的长度,但不能计算包含有TAB符的字符串的长度。

2.
BOOL GetTextExtentExPoint(
HDC hdc, // handle to device context
LPCTSTR lpszStr, // pointer to character string
int cchString, // number of characters in string
int nMaxExtent, // maximum width for formatted string
LPINT lpnFit, // pointer to value specifying max. number of
// chars.
LPINT alpDx, // pointer to array for partial string widths
LPSIZE lpSize // pointer to structure with string dimensions
);
此函数比上一个函数的好处是它可以计算在nMaxExtent宽度内可以容纳的字符的个数,并且可以返回每一个字符的宽度。不过它还是不能正确计算包含有TAB符的字符串的长度。

3.
int DrawText(
HDC hDC, // handle to device context
LPCTSTR lpString, // pointer to string to draw
int nCount, // string length, in characters
LPRECT lpRect, // pointer to struct with formatting dimensions
UINT uFormat // text-drawing flags
);
此函数uFormat参数中有DT_CALCRECT标志,则可以进行计算字符串的显示区域(长和宽)。注意:如只要计算字符串的宽度,就要包含DT_SINGLELINE标志。它也不能正确计算包含有TAB符的字符串的长度。

4.
int DrawTextEx(
HDC hdc, // handle to device context
LPTSTR lpchText, // pointer to string to draw
int cchText, // length of string to draw
LPRECT lprc, // pointer to rectangle coordinates
UINT dwDTFormat, // formatting options
LPDRAWTEXTPARAMS lpDTParams // pointer to struct with options
);
此函数是上一个函数的扩展,它可以计算包含有TAB字符的字符串的正确宽度。

以上列出的函数各有所长,在应用中要根据实际情况选择最适合的函数。另外要注意的是,在使用这些函数前,设备环境(DC或Canvas)要选入特定的字体,如Canvas.Font := XXX; 或
SelectObject( Canvas.Handle, xFont.Handle );

5,379

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧