Reputation: 3486
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?
Upvotes: 2
Views: 2637
Reputation:
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;
Upvotes: 2
Reputation: 1245
If you want to update your rectangle before drawing the text you could use DT_CALCRECT. DrawText will then modify your rectangle to the new height (and width if necessary). If you only need the height though use the return value as Andreas Rejbrand showed.
Here's a sample of this:
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;
I would recommend reading the docs for more details: http://msdn.microsoft.com/en-us/library/dd162498(v=vs.85).aspx
Upvotes: 2
Reputation: 108963
The height of the drawn text is the returned value of DrawText
.
HeightOfText := DrawText(...
Upvotes: 4