2011. február 10., csütörtök
How to calculate the line length of a TRichEdit
Problem/Question/Abstract:
I want to fill a whole line with the same char in a TRichEdit but I can't figure out how I could retrieve the maximum char number for a line.
Answer:
The number of characters you would be able to fit into a line depends on the font and the character used (unless the font is fixed-pitch). The first order of the day is to find out how much space is available for the line. This you do by asking the control for its formatting rectangle, which is usually a bit smaller than the client area. Then you determine the font to use and measure the character, which gives you a first estimate of the number of characters that may fit. You construct a string of this character of the calculated length and measure it again. It may turn out to be too long since the length also includes intercharacter distance, so you remove characters till it fits.
function MakeLine(re: TRichEdit; ch: Char): string;
var
cv: TControlCanvas;
r: TRect;
max, len: Integer;
begin
cv := TControlCanvas.Create;
try
cv.Control := re;
cv.Font.Assign(re.SelAttributes);
re.Perform(EM_GETRECT, 0, lparam(@r));
max := r.right - r.Left;
len := max div cv.TextWidth(ch);
Result := StringOfChar(ch, len);
while cv.TextWidth(result) > max do
Delete(result, Length(Result), 1);
finally
cv.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
richedit1.SelText := MakeLine(richedit1, '-');
end;
You may want to enhance this to take account of any margin settings in the current paragraph.
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése