在Delphi中,我希望在TRect中绘制文本.我希望有以下功能:
>在TRect中垂直居中绘制文本
>在TRect中水平居中绘制文本
>如果有超过1行文本的空间(使用TRect的高度),则绘制文本多行
>如果文本不适合TRect(在单行或多行上),则将省略号附加到文本中.
解决方法
对不起,这是以前所有答案和评论的组合.但似乎OP需要更多的帮助.
function DrawTextCentered(Canvas: TCanvas; const R: TRect; S: String): Integer; var DrawRect: TRect; DrawFlags: Cardinal; DrawParams: TDrawTextParams; begin DrawRect := R; DrawFlags := DT_END_ELLIPSIS or DT_NOPREFIX or DT_WORDBREAK or DT_EDITCONTROL or DT_CENTER; DrawText(Canvas.Handle,PChar(S),-1,DrawRect,DrawFlags or DT_CALCRECT); DrawRect.Right := R.Right; if DrawRect.Bottom < R.Bottom then OffsetRect(DrawRect,(R.Bottom - DrawRect.Bottom) div 2) else DrawRect.Bottom := R.Bottom; ZeroMemory(@DrawParams,SizeOf(DrawParams)); DrawParams.cbSize := SizeOf(DrawParams); DrawTextEx(Canvas.Handle,DrawFlags,@DrawParams); Result := DrawParams.uiLengthDrawn; end; procedure TForm1.FormPaint(Sender: TObject); const S = 'This is a very long text as test case for my paint routine.'; var R: TRect; begin SetRect(R,100,200,140); Canvas.Rectangle(R); InflateRect(R,-1); Caption := Format('%d characters drawn',[DrawTextCentered(Canvas,R,S)]); end;