Delphi - 在矩形的中心绘制文本多行 [英] Delphi - Draw text multiline in the centre of a rect

查看:22
本文介绍了Delphi - 在矩形的中心绘制文本多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Delphi 中,我希望在 TRect 内绘制文本.我希望有以下功能:

In Delphi i wish to draw text inside a TRect. I am hoping for the following functionality:

  1. 在 TRect 内垂直居中绘制文本
  2. 在 TRect 中水平居中绘制文本
  3. 如果有超过 1 行文本的空间(使用 TRect 的高度),绘制文本多行
  4. 如果文本不适合 TRect(在单行或多行中),则在文本后附加省略号.

我可以看到 Windows.DrawText() 函数几乎涵盖了此功能,但是在编写文本时,多行和垂直居中是相互排斥的.

I can see the Windows.DrawText() function almost covers this functionality, however when writing text, multiline and vertically centred are mutually exclusive.

我想知道此功能是否内置于 Windows (2000+) 中?如果没有,有没有办法在不编写自己的函数的情况下做到这一点?

I was wondering if this functionality is built into windows (2000+)? If not is there a way to do this without writing my own function?

推荐答案

抱歉,这是之前所有答案和评论的组合.但似乎 OP 需要更多帮助.

Sorry, this is a combination of all previous answers and comments. But it seems OP needs more assistance.

function DrawTextCentered(Canvas: TCanvas; const R: TRect; S: String): Integer;
var
  DrawRect: TRect;
  DrawFlags: Cardinal;
  DrawParams: TDrawTextParams;
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;
  ZeroMemory(@DrawParams, SizeOf(DrawParams));
  DrawParams.cbSize := SizeOf(DrawParams);
  DrawTextEx(Canvas.Handle, PChar(S), -1, DrawRect, DrawFlags, @DrawParams);
  Result := DrawParams.uiLengthDrawn;
end;

procedure TForm1.FormPaint(Sender: TObject);
const
  S = 'This is a very long text as test case for my paint routine.';
var
  R: TRect;
begin
  SetRect(R, 100, 100, 200, 140);
  Canvas.Rectangle(R);
  InflateRect(R, -1, -1);
  Caption := Format('%d characters drawn', [DrawTextCentered(Canvas, R, S)]);
end;

这篇关于Delphi - 在矩形的中心绘制文本多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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