使用WinAPI" DrawText"绘制垂直居中的多行字符串。函数

时间:2017-06-07 09:45:14

标签: windows winapi

我正在尝试使用WinAPI的DrawText函数在位图中垂直和水平居中绘制一个包含字的字符串。

问题在于,如果文字比可用空间长,并且" END ELLIPSIS" (...)被添加到裁剪的字符串中,使用" DT_CALCRECT"时返回报告的绘图坐标。通过垂直居中计算报告未加工的线条数量。

我在这上面阅读了很多帖子,并认为" Delphi - Draw text multiline in the centre of a rect"可能会得到答案,但它没有(使用链接问题http://zoomplayer.com/pix/font_vcenter.jpg中的示例输出代码的屏幕截图)。接受的答案的作者建议我创建一个新问题,所以在这里。

为了快速参考,这里是链接的接受答案的略微简化(删除不相关的代码)文本呈现代码:

procedure DrawTextCentered(Canvas: TCanvas; const R: TRect; S: String);
var
  DrawRect: TRect;
  DrawFlags: Cardinal;
begin
  DrawRect := R;
  DrawFlags := DT_END_ELLIPSIS or DT_NOPREFIX or DT_WORDBREAK or
    DT_EDITCONTROL or DT_CENTER;
  DrawText(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags or DT_CALCRECT);
  DrawRect.Right := R.Right;
  if DrawRect.Bottom < R.Bottom then
    OffsetRect(DrawRect, 0, (R.Bottom - DrawRect.Bottom) div 2)
  else
    DrawRect.Bottom := R.Bottom;
  DrawTextEx(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags, nil);
end;

从屏幕截图中可以看出,问题出现在使用&#34; DT_CALCRECT&#34;初始调用DrawText之后。标记以测量输出高度以便以后垂直居中,渲染字符串&#34;趋势:全球&#34;返回表示3行文本的DrawRect.Bottom值,即使只绘制了2行,也会破坏垂直居中代码。

0 个答案:

没有答案
相关问题