2015-09-30 36 views
1

您好堆棧溢出用戶確定的TLabel的寬度

我有它TGroupBoxTLabel。有了這個TLabel我想顯示候選人的姓氏和名字。有些候選人有不止一個姓名,有時候會有三個,發生這種情況時,TLabel並不總是適合我的TGroupBox。當發生這種情況時,我只顯示姓氏,名字,其餘的我只是首字母。

爲了做到這一點,我需要知道TLabel是否適合如果值分配給它。換句話說,我需要確定在將值分配給其Caption屬性之前,將會有多大的TLabel寬度,因爲這會對編程顯示不良數據。

有什麼建議嗎?

+0

您使用的是VCL還是FMX? –

回答

1

我發現了一個非常簡單的方法來做到這一點。基本上,你只是想知道一個字符串的像素寬度,所以最好的方法是動態創建一個具有FontCanvas屬性的對象。我認爲TBitmap將是最好的選擇。這裏是我使用的代碼:

var 
    sString: string; 
    bmWidth: TBitmap; 
    iWidth: Integer; 
begin 
    sString := edtEdit.Text; 
    bmWidth := TBitmap.Create; 
    try 
    bmWidth.Canvas.Font.Assign(lblLabel.Font); 
    iWidth := bmWidth.Canvas.TextWidth(sString); 
    finally 
    bmWidth.Free; 
    end; 
end; 
1

在VCL,TLabel使用Win32 API DrawText()函數來計算文本寬度,使用GetDC()得到屏幕的HDC然後SelectObject()選擇當前FontHDC。你將不得不做同樣在自己的代碼,如:

// set Label1.AutoSize to False and Label1.Width to 
// the max width your UI will accept the Label1 to be... 

function WillFitInLabel(Label: TLabel; const S: String): Boolean; 
var 
    R: TRect; 
    C: TCanvas; 
    DC: HDC; 
begin 
    R := Rect(0, 0, Label.Width, 0); 
    C := TCanvas.Create; 
    try 
    DC := GetDC(0); 
    try 
     C.Handle := DC; 
     try 
     C.Font := Label1.Font; 
     Windows.DrawText(DC, PChar(S), Length(S), R, DT_SINGLELINE or DT_CALCRECT); 
     finally 
     C.Handle := 0; 
     end; 
    finally 
     ReleaseDC(0, DC); 
    end; 
    finally 
    C.Free; 
    end; 
    Result := (R.Width <= Label.Width); 
end; 

var 
    Names: String; 
begin 
    Names := ...; 
    if WillFitInLabel(Label1, Names) then 
    Label1.Caption := Names 
    else 
    ... 
end; 
+1

參見'TCanvas.TextWidth'([VCL](http://docwiki.embarcadero.com/Libraries/en/Vcl.Graphics.TCustomCanvas.TextWidth)和[FMX](http://docwiki.embarcadero.com/庫/ EN/FMX.Graphics.TCanvas.TextWidth))。 –

+0

在VCL中,'TCanvas.TextWidth()'使用Win32的'GetTextExtentPoint32()'函數,它不像Win32'DrawText()'函數那樣計算事物。 TLabel使用DrawText()來進行計算和繪圖。 –

0

如果你想在包裝線多長文本,那麼你可以使用標籤的屬性WordWrap := TrueAutoSize := True