这是这样做的:
procedure DrawTextNOT(const hDC: HDC; const Font: TFont; const Text: string; const X, Y: integer);
begin
with TBitmap.Create do
try
Canvas.Font.Assign(Font);
with Canvas.TextExtent(Text) do
SetSize(cx, cy);
Canvas.Brush.Color := clBlack;
Canvas.FillRect(Rect(0, 0, Width, Height));
Canvas.Font.Color := clWhite;
Canvas.TextOut(0, 0, Text);
BitBlt(hDC, X, Y, Width, Height, Canvas.Handle, 0, 0, SRCINVERT);
finally
Free;
end;
end;
Example:
procedure TForm1.FormClick(Sender: TObject);
begin
Canvas.Brush.Color := clRed;
Canvas.FillRect(ClientRect);
DrawTextNOT(Canvas.Handle, Canvas.Font, 'This is a test.', 20, 100);
// DrawTextNOT(Canvas.Handle, Canvas.Font, 'This is a test.', 20, 100);
end;
您可能还想禁用 ClearType。为此,我建议您参考之前的一个SO问题 https://stackoverflow.com/questions/3716304/is-there-a-way-to-disable-font-anti-aliasing-when-using-textrect-aka-exttextout.