對不起,這是以前的所有答案和評論的組合。但似乎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, 0, (R.Bottom - DrawRect.Bottom) div 2)
else
DrawRect.Bottom := R.Bottom;
ZeroMemory(@DrawParams, SizeOf(DrawParams));
DrawParams.cbSize := SizeOf(DrawParams);
DrawTextEx(Canvas.Handle, PChar(S), -1, DrawRect, 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, 100, 200, 140);
Canvas.Rectangle(R);
InflateRect(R, -1, -1);
Caption := Format('%d characters drawn', [DrawTextCentered(Canvas, R, S)]);
end;
難道你不能使用TLabel?我認爲它具有所需的全部功能。 –
是的,它可能會做,但我不想使用標籤,我有一個畫布可以畫畫。 – Simon