4

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?

Community
  • 1
  • 1
NaN
  • 8,596
  • 20
  • 79
  • 153

2 Answers2

5

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;
Community
  • 1
  • 1
NGLN
  • 43,011
  • 8
  • 105
  • 200
5

An easier way with more possibilities will be:

Canvas.TextRect(Rect,s,[tfCenter,tfVerticalCenter,tfSingleLine]);
NGLN
  • 43,011
  • 8
  • 105
  • 200
bummi
  • 27,123
  • 14
  • 62
  • 101
  • @NGLN, @bummi, `There is no overloaded version of '%s' that can be called with these arguments (E2250)` – NaN Nov 14 '12 at 17:19
  • Oh sorry, I thought I had found a reference of it being present in D2005, but apparently it isn't in D2006 yet! – NGLN Nov 14 '12 at 17:23