Delphi - Draw text multiline in the centre of a rect

后端 未结 2 960
余生分开走
余生分开走 2020-12-10 06:20

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

  1. Draw the text centred vertically within the TRect
  2. Draw the
相关标签:
2条回答
  • 2020-12-10 06:26

    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;
    
    0 讨论(0)
  • 2020-12-10 06:39

    Measure the text first using DT_CALCRECT. Pass DT_WORDBREAK to specify that word wrapping is enabled. This will allow you to find the required height for your text. Then you can, in your code, calculate the vertical offset that gives you vertically centred text, and draw to that offset.

    0 讨论(0)
提交回复
热议问题