Align cells in a TStringGrid (4) (Views: 773)
Problem/Question/Abstract: Anyone know a simple way of vertically centering your text in a TStringGrid cell. Actually, I wish the StringGrid had the ability to align horizontally as well. Answer: Below is some Delphi3 code that I wrote for handling left-right alignment of text in string grids. It would be straightforward to change it for vertical instead (or as well). See DT_BOTTOM, DT_VCENTER and DT_TOP in the description of DrawText in Delphi's Win32 help file. The code also handles automatic word-wrapping and font changes on a per cell basis. procedure DrawSGCell(Sender: TObject; C, R: integer; Rect: TRect; Style: TFontStyles; Wrap: boolean; Just: TAlignment; NoEditCols: TNoEditCols); {formats cell text; call this routine from grid's DrawCell event; Style is TFontStyles... TFontStyles = set of TFontStyle; TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut); Wrap is word-wrap on/off, Just is (taLeftJustify, taRightJustify, taCenter)} var S: string; DrawRect: TRect; begin {multi-line wordwrapped cells, with any justification, and any font params} {if Row > 0 then { only used for column headings} exit; } { get cell contents } with (Sender as TStringGrid), Canvas do begin S := Cells[C, R]; {erase earlier contents from default drawing } Brush.Color := FixedColor; if (R >= FixedRows) and (C >= FixedCols) and not (C in NoEditCols) then Brush.Color := Color; FillRect(Rect); if length(S) > 0 then begin {switch to font style} Font.Style := Style; {local copy of cell rectangle} DrawRect := Rect; if Wrap then begin {get size of text rectangle in DrawRect} DrawText(Handle, PChar(S), length(S), DrawRect, dt_calcrect or dt_wordbreak or dt_center); if (DrawRect.Bottom - DrawRect.Top) > RowHeights[R] then begin {cell word-wrapped; need to increase row height} RowHeights[R] := DrawRect.Bottom - DrawRect.Top; SetGridHeight(Sender as TStringGrid); end else begin DrawRect.Right := Rect.Right; FillRect(DrawRect); case Just of taLeftJustify: begin S := ' ' + S; DrawText(Handle, PChar(S), length(S), DrawRect, dt_wordbreak or dt_left); end; taCenter: DrawText(Handle, PChar(S), length(S), DrawRect, dt_wordbreak or dt_center); taRightJustify: begin S := S + ' '; DrawText(Handle, PChar(S), length(S), DrawRect, dt_wordbreak or dt_right); end; end; end; end else {no wrap} case Just of taLeftJustify: begin S := ' ' + S; DrawText(Handle, PChar(S), length(S), DrawRect, dt_singleline or dt_vcenter or dt_left); end; taCenter: DrawText(Handle, PChar(S), length(S), DrawRect, dt_singleline or dt_vcenter or dt_center); taRightJustify: begin S := S + ' '; DrawText(Handle, PChar(S), length(S), DrawRect, dt_singleline or dt_vcenter or dt_right); end; end; {restore no font styles} Font.Style := []; end; end; end; |