DrawText with DT_CALCRECT - 有没有办法计算矩形的高度而不修改宽度(使用大字符串)?
我有一个字符串,需要在绘图时计算矩形大小(文本高度)。我的实现使用带有 DT_WORDBREAK 或 DT_CALCRECT 标志的 DrawTextW()
函数。
我的字符串的示例:
thisisaverylonglonglonglineoftextthatneedstofitinsideagivenrectwidth
我可以在 中看到MSDN 文档中,DrawTextW()
方法指出:
如果最大的单词比矩形宽,则宽度会扩大。如果文本小于矩形的宽度,则宽度会减小。如果只有一行文本,DrawText 会修改矩形的右侧,以便它限制该行中的最后一个字符。
但是在 MSDN 文档中,DrawTextExW()
方法没有说明这一点。
因此,我尝试使用 DrawTextExW()
方法计算高度,但结果与 DrawTextW()
函数相同,它将矩形的宽度扩展到适合最大的文本行。
那么,在绘制指定了 DT_WORDBREAK 和 DT_CALCRECT 的大字符串(没有空格)时,如何正确计算具有给定(固定)宽度的文本矩形的高度?
编辑:
顺便说一句,有人知道 Microsoft Excel 如何绘制单元格文本吗?是否有针对此文本绘制的 API 调用?这是我最初的问题的根源,但是它在 Excel 中实现的方式是在任何字符(不仅仅是空格)上绘制文本和断字/自动换行。
I have a string that i need to calculate the Rect size (text height) when drawing. My implementation uses the DrawTextW()
function with DT_WORDBREAK or DT_CALCRECT
flags.
An example of my string:
thisisaverylonglonglonglineoftextthatneedstofitinsideagivenrectwidth
I can see in the MSDN docs, that DrawTextW()
method states:
If the largest word is wider than the rectangle, the width is expanded. If the text is less than the width of the rectangle, the width is reduced. If there is only one line of text, DrawText modifies the right side of the rectangle so that it bounds the last character in the line.
however in the MSDN docs, then DrawTextExW()
method does not state this.
So i tried to calculate the height using the DrawTextExW()
method, however the result is the same as with DrawTextW()
function, where it extends the width of the rect to fit the largest line of text.
So how can i correctly calculate the height of the text rect with a given (fixed) width when drawing a large string (with no spaces) where DT_WORDBREAK
and DT_CALCRECT
are specified?
EDIT:
As a side note, does anyone know how Microsoft Excel does cell text drawing? Is there an API call for this text drawing? This was where my original question stemmed from, however the way it is implemented in Excel is to draw the text and wordbreak/wordwrap on any character (not just a space).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在
uFormat
参数中使用DT_WORD_ELLIPSIS
标志(当然还有DT_WORDBREAK
)。这将防止由于没有空格的长字符串而变宽。它仍然不会破坏那些长字符串,但你的宽度问题将得到解决。如果您还指定了
DT_MODIFYSTRING
,那么您可以在最终绘制之前找出自己在哪里断开该长字符串。至于
DrawText(W)
和DrawTextEx(W)
之间的区别:后者提供制表符格式、设置边距并返回实际绘制的字符数。 (尺寸)功能没有差异。You need to use the
DT_WORD_ELLIPSIS
flag inuFormat
parameter (along withDT_WORDBREAK
of course). That will prevent the widening due to long strings with no spaces. It still will not break those long strings though, but your width problem will be solved.If you also specify
DT_MODIFYSTRING
, then you could kind of figure out where to break that long string yourself, prior to the final draw.As for the difference between
DrawText(W)
andDrawTextEx(W)
: the latter provides tab formatting, setting margins and returns the actual number of drawn characters. There is no difference in (dimensioning) functionality.