Delphi: How to draw text in the requested width and number of lines with a finite ellipse?

I need to draw text in a table cell with a fixed width (in pixels) and a fixed number of text lines. If the text is cropped by the rectangle of the cell, it must end with an ellipsis. The problem is that I cannot correctly calculate the rectangle of the text (or the TextRect / DrawText procedure does not work correctly, I'm not sure).

I tried using this method to calculate a text rectangle:

var TextRect: TRect; tm: TEXTMETRIC; ... GetTextMetrics(Canvas.Handle, tm); TextLineHeight := tm.tmHeight + tm.tmExternalLeading; TextRect.Bottom := TextRect.Top + TextLineHeight * NumberOfLines; Canvas.TextRect(TextRect, 'some long long long text', [tfTop, tfLeft, tfEndEllipsis, tfWordBreak]); 

The clipping rectangle is calculated correctly, but the ellipsis does not appear.

The ellipsis appears when I reduce the clipping height of the rectangle by 1 pixel:

 TextRect.Bottom := TextRect.Top + TextLineHeight * NumberOfLines - 1; 

But some pixels of the bottom line of my text are cropped then.

How to do it right?

+4
source share
2 answers

Since api sets the final ellipsis only when the last line does not match the specified rectangle, one way could be to specify tfModifyString in the formatting options when you first call TextRect with a rectangle with a reduced height, then call "TextRect" again with a rectangle of the corresponding size and changed text :

 var Text: string; ... Text := 'some long long long text'; SetLength(Text, Length(Text) + 4); // as per DrawTextEx documentation Dec(TextRect.Bottom); Canvas.TextRect(TextRect, Text, [tfTop, tfLeft, tfEndEllipsis, tfWordBreak, tfModifyString]); Inc(TextRect.Bottom); Canvas.TextRect(TextRect, Text, [tfTop, tfLeft, tfWordBreak]); 


I would make sure that in the future the OS version decides to completely fix the last line if it does not fit completely into the rectangle .. :)

+4
source

I would try to calculate the necessary rectangle via Canvas.TextRect(..., [tfCalcRect, ...]) .

0
source

Source: https://habr.com/ru/post/1346515/


All Articles