unit Unit2;
interface
uses
System.SysUtils,
System.StrUtils;
type
TCharMeasureWidthDelegate =
function(
const C: Char ): Integer
of object;
function ShortenText(
const Text:
string;
const MaxLength: Integer;
const CharMeasurement: TCharMeasureWidthDelegate;
const ShortenSuffix:
string = '
...' ):
string;
implementation
function ShortenText(
const Text:
string;
const MaxLength: Integer;
const CharMeasurement: TCharMeasureWidthDelegate;
const ShortenSuffix:
string = '
...' ):
string;
var
lText :
string;
lChar : Char;
lCharLength : Integer;
lSuffixLength : Integer;
lTextLength : Integer;
lShortenedWithSuffix :
string;
lShortendWithSuffixFound: Boolean;
begin
if not Assigned( CharMeasurement )
then
raise EArgumentNilException.Create( '
CharMeasurement' );
if MaxLength < 0
then
raise EArgumentOutOfRangeException.Create( '
MaxLength' );
lSuffixLength := 0;
for lChar
in ShortenSuffix
do
begin
lSuffixLength := lSuffixLength + CharMeasurement( lChar );
end;
if lSuffixLength > MaxLength
then
raise EArgumentOutOfRangeException.Create( '
SuffixLength > MaxLength' );
Result := '
';
lText := TrimRight( Text );
lTextLength := 0;
lShortendWithSuffixFound := False;
for lChar
in lText
do
begin
lCharLength := CharMeasurement( lChar );
if not lShortendWithSuffixFound
and ( lTextLength + lCharLength + lSuffixLength > MaxLength )
then
begin
lShortenedWithSuffix := Result + ShortenSuffix;
lShortendWithSuffixFound := True;
end;
if lTextLength + lCharLength > MaxLength
then
begin
Result := lShortenedWithSuffix;
Exit;
end;
Result := Result + lChar;
Inc( lTextLength, lCharLength );
end;
end;
end.