Author: Jonas Bilinkevicius
How can I find the length of a string drawn in a particular font? For instance,
Edit1 has the text of 'Hello World' in Arial bold, size = 16.
Answer:
Solve 1:
You measure it using the TextWidth method of a canvas into which the font has been
copied. You can usually use the forms Canvas for this kind of work since it is not
used anywhere else (unless you have a handler for the OnPaint event). The typcial
code would be:
canvas.font := edit1.font; {edit1.font has size etc. to measure}
aTextwidth := canvas.TextWidth(someText);
One problem with this approach is that it will fail if you do the measuring at a
time the form does not have a window handle yet. I prefer to use a dynamically
created canvas for this kind of task:
1 2 function CalcMaxWidthOfStrings(aList: TStrings; aFont: TFont): Integer;
3 var4 max, n, i: Integer;
5 canvas: TCanvas;
6 begin7 Assert(Assigned(aList));
8 Assert(Assigned(aFont));
9 canvas := TCanvas.Create;
10 try11 canvas.Handle := CreateDC('DISPLAY', nil, nil, nil);
12 try13 Canvas.Font := aFont;
14 max := 0;
15 for i := 0 to aList.Count - 1 do16 begin17 n := Canvas.TextWidth(aList[i]);
18 if n > max then19 max := n;
20 end;
21 Result := max;
22 finally23 DeleteDC(canvas.Handle);
24 canvas.Handle := 0;
25 end;
26 finally27 canvas.free;
28 end;
29 end;
30 31 32 //Solve 2:33 34 function GetTextWidthInPixels(AText: string; AControl: TControl): integer;
35 var36 propInfo: PPropInfo;
37 thisFont: TFont;
38 begin39 Result := 0;
40 propInfo := GetPropInfo(AControl.ClassInfo, 'Font');
41 if propInfo <> nilthen42 begin43 thisFont := TFont(GetObjectProp(AControl, 'Font'));
44 if Assigned(thisFont) then45 with TControlCanvas.Create do46 try47 Control := AControl;
48 Font.Assign(thisFont);
49 Result := TextWidth(AText);
50 finally51 Free;
52 end;
53 end;
54 end;
55 56 //Call with:57 58 twidth := GetTextWidthInPixels(Edit1.Text, Edit1);