본문 바로가기

프로그래밍/Delphi

DrawText를 이용한 WrapedText의 높이 구하기


DrawText를 이용하여 고정된 Width를 갖는 TEXTBOX에 DRAW했을 경우에 해당 TEXTBOX의 높이를 알 수 있다.
아래 샘플코드는 DrawText를 이용하여 Wraped된 TEXT를 출력합니다.
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; 
Wraped된 TEXT를 Draw하기 전에 Draw될 사각 영역을 알기 위하여 DrawText 함수내 선택 인자 "DT_CALCRECT"를 이용할 수 있습니다. DrawText는 이 옵션을 사용하여 새로운 사각 영역의 높이를 알 수 있다(넓이도 ...) "DT_CALCRECT" 옵션을 사용할때 함께 주어지는 사각 영역 "R" 값에 입력에는 넓이 값을 지정하게 되고 함수 수행후 R값에는 Bottom 값에 변경된 높이(height)값이 반환되어 들어옵니다. 아래 예문은 먼저 출력될 문자열을 "DT_CALCRECT"를 이용하여 새로운 높이를 알아 낸 다음에 실제로 다시 DrawText를 이용하여 Draw하고 바로 아래 라인에 다시 재 출력하는 예제 입니다.
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;
DrawText함수에 "DT_CALCRECT"플래그를 지정함으로써 실제로는 아무것도 Display 하지 않으면서 실제 출력할 대상 영역에 대한 정보를 변수 "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;
위와 같이 R에 리턴되는 값을 이용하여 아래 예제처럼 두번을 연속해서 다른 플래그를 지정하여 실제 Draw까지 할 수 있습니다
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;