1

code sample

procedure TForm1.Button1Click(Sender: TObject);
var
  r: Trect;
  s: String;
begin
  R := Rect(0,0, 300, 100);
  s := 'WordWrapTextOut(TargetCanvas: TCanvas; var x, y: integer; S: string; maxwidth, lineheight: integer);';
  DrawText(Canvas.Handle, PChar(s),  length(s), R, DT_WORDBREAK or DT_LEFT);
end;

I want to wrap the text in 300px width but how can I get the new Height? Is there a way or any solution?

4

3 回答 3

4

绘制文本的高度是 的返回值DrawText

HeightOfText := DrawText(...
于 2011-06-22T11:17:48.317 回答
1

As was mentioned here you can get it by calling DrawText function with DT_CALCRECT flag specified what actually won't paint anything; it just calculates appropriate rectangle and returns it to variable R.

procedure TForm1.Button1Click(Sender: TObject);
var
  R: TRect;
  S: String;
begin
  R := Rect(0, 0, 20, 20);
  S := 'What might be the new high of this text ?';
  DrawText(Canvas.Handle, PChar(S), Length(S), R, DT_WORDBREAK or DT_LEFT or DT_CALCRECT);
  ShowMessage('New height might be '+IntToStr(R.Bottom - R.Top)+' px');
end;

What means if you call it twice using the following example, you'll get drawn the wrapped text. It's because the first call with DT_CALCRECT calculates the rectangle (and modify R variable by doing it) and the second call draws the text in that modified rectangle area.

procedure TForm1.Button1Click(Sender: TObject);
var
  R: TRect;
  S: String;
begin
  R := Rect(0, 0, 20, 20);
  S := 'Some text which will be stoutly wrapped and painted :)';
  DrawText(Canvas.Handle, PChar(S), Length(S), R, DT_WORDBREAK or DT_LEFT or DT_CALCRECT);
  DrawText(Canvas.Handle, PChar(S), Length(S), R, DT_WORDBREAK or DT_LEFT);
end;
于 2011-06-22T21:00:43.013 回答
1

如果你想在绘制文本之前更新你的矩形,你可以使用 DT_CALCRECT。然后,DrawText 会将您的矩形修改为新的高度(如果需要,还可以修改宽度)。如果您只需要高度,请使用 Andreas Rejbrand 显示的返回值。

这是一个示例:

procedure TForm1.Button1Click(Sender: TObject);
var
  r: Trect;
  s: String;
begin
  R := Rect(0,0, 300, 100);
  s := 'WordWrapTextOut(TargetCanvas: TCanvas; var x, y: integer; S: string; maxwidth, lineheight: integer);';
  if DrawText(Canvas.Handle, PChar(s),  length(s), R, DT_CALCRECT or DT_WORDBREAK or DT_LEFT) <> 0 then
  begin
    DrawText(Canvas.Handle, PChar(s),  length(s), R, DT_WORDBREAK or DT_LEFT);
    r.Top := r.Bottom;
    r.Bottom := r.Bottom * 2;
    DrawText(Canvas.Handle, PChar(s),  length(s), R, DT_WORDBREAK or DT_LEFT);
  end;
end;

我建议阅读文档以获取更多详细信息:http: //msdn.microsoft.com/en-us/library/dd162498 (v=vs.85).aspx

于 2011-06-22T17:11:49.310 回答