How to calculate the "Left" property to center the text in a DBGrid cell?

The continuation of the project began with:

How to automatically select / scale the width of DBGrid columns (or other similar ones) according to its contents?

How to calculate the "Left" property to center the text in a DBGrid cell?

When we call OnDrawColumnCell and use Canvas to write text instead of replacing the default mesh, how can we calculate the position of the text when we want to center it in the cell?

+4
source share
2 answers

not to do. Draw the text DrawText / DrawTextEx and specify DT_CENTER in the format parameter. See Also Draw multi-line text in the center of the rectangle .

Or, if you need 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; 
+5
source

An easier way with more features would be:

 Canvas.TextRect(Rect,s,[tfCenter,tfVerticalCenter,tfSingleLine]); 
+5
source

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


All Articles