Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the "Left" Property to center a Text in a DBGrid Cell?

Continuing with the project started in:

How to auto fit/scale DBGrid's (or other similar) columns widths according to its contents?

How to calculate the "Left" Property to center a Text in a DBGrid Cell?

When we call OnDrawColumnCell and use the Canvas to write a text in replacement of the default draw of the grid, how may we calculate the position of the text when we want to center it on the cell?

like image 713
NaN Avatar asked Dec 27 '22 14:12

NaN


2 Answers

Don't. Paint the text with DrawText/DrawTextEx and specify DT_CENTER in the format parameter. See also Draw text multiline in the centre of a rect.

Or if you want or need to calculate it yourself:

procedure DrawCenteredText(Canvas: TCanvas; const S: String; R: TRect);
var
  Left: Integer;
begin
  Left := R.Left + (R.Right - R.Left - Canvas.TextWidth(S)) div 2;
like image 123
NGLN Avatar answered Mar 02 '23 00:03

NGLN


An easier way with more possibilities will be:

Canvas.TextRect(Rect,s,[tfCenter,tfVerticalCenter,tfSingleLine]);
like image 33
bummi Avatar answered Mar 02 '23 01:03

bummi