Question

Is there an ellipsis / ellipsify routine for shortening button or label text in Firemonkey? eg, to turn:

"C:\a really\really\really long\very long path\even longer path name" into "C:\a really\re..." or "C:\a really\re...path name"

There are routines around for VCL but it looks like finding Firemonkey's text size will be more involved.

I am using Firemonkey 2 on Delphi XE3

Thanks in advance

... Ok I've created a clunky procedure from Mike Sutton's advice. It only adds the ellipsis at the end of the 1st part of the string but could be modified quite easily for middle or end ellipsis positions. It also takes into account the current objects Font size and style.

Usage would be:

ShortenText(Button1, 'Start of text blah blah blah blah the END is here');

procedure ShortenText(anFMXObject: TTextControl; newText: string);
var
  aTextObj: TText;
  shortenTo: integer;
  modText: string;
begin
  if Length(newText) > 2 then
  begin
    modText:= newText+'...';
    aTextObj:=TText.Create(anFMXObject.Parent);
    aTextObj.Font.SetSettings(anFMXObject.Font.Family,
                          anFMXObject.Font.Size,
                          anFMXObject.Font.Style);
    aTextObj.WordWrap:= false;
    aTextObj.AutoSize:= true;
    aTextObj.Text:= newText;
    // this next bit generates the change necessary to redraw the new text (bug in XE3 as of Oct 2012)
    aTextObj.HorzTextAlign:= TTextAlign.taCenter;
    aTextObj.HorzTextAlign:= TTextAlign.taLeading;
    // now shorten the text:
    shortenTo:= round((Length(modText)/aTextObj.Width)*anFMXObject.Width)-1;
    modText:= LeftStr(modText, shortenTo-3)+'...';
    anFMXObject.Text:= modText;
    FreeAndNil(aTextObj);
  end;
end;
Was it helpful?

Solution

I would suggest using a TText with AutoSize set to True and Wrap set to False then you can simply read the Width property.

Note that there's a bug in XE3 and setting the Text property at run-time doesn't update the contents, so you'll want to manually call Realign (which is protected, so you'll want to subclass TText to get this to work).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top