Hello Stack Overflow Users
I have a TGroupBox
with a TLabel
in it. With this TLabel
I want to display the surname and names of a candidate. Some candidates have more than one name, sometimes three, and when that happens, the TLabel
doesn't always fit inside my TGroupBox
. When that happens, I only display the surname, the first name, and the rest I only as initials.
In order to do this, I need to know whether the TLabel
is going to fit if the values were to be assigned to it. In other words, I need to determine what the width of the TLabel
is going to be before actually assigning the values to its Caption
property, for that would be bad programming to display variable data.
Any suggestions?
I found a very easy and short way to do this. Basically, you just want to know the width of a string in pixels, so the best way to achieve this is to dynamically create an object that has a Font
and Canvas
property. I thought TBitmap
will be the best option. Here’s the code I used:
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;