Is there a way to disable font anti aliasing when

2019-01-24 21:32发布

问题:

I'm using a custom gauge, based on the example that came with Delphi (5 Enterprise). For those that don't know, it's like a smooth progress bar, but displays the percentage or value in the centre (vertically and horizontally) of the component.

To make sure the text is readable both when the gauge is filled and when it's empty, the text is displayed using inverted colours.

When font anti-aliasing is used, these inverted colours cause the edge of the font to appear in really crazy colours, ruining the look of the component.

Is there any way to disable font smoothing / anti aliasing for just this one component, or disable it, draw the text, then re-enable it?

My current workaround is to use a font that doesn't get smoothed, like "MS Sans Serif", but I'd like to use the same font as the rest of the UI for consistency.

回答1:

Specifying NONANTIALIASED_QUALITY in the LOGFONT structure should turn antialiasing off:

procedure SetFontQuality(Font: TFont; Quality: Byte);
var
  LogFont: TLogFont;
begin
  if GetObject(Font.Handle, SizeOf(TLogFont), @LogFont) = 0 then
    RaiseLastOSError;
  LogFont.lfQuality := Quality;
  Font.Handle := CreateFontIndirect(LogFont);
end;

procedure TForm1.PaintBox1Paint(Sender: TObject);
const
  FontQualities: array[Boolean] of Byte = (DEFAULT_QUALITY, NONANTIALIASED_QUALITY);
var
  Canvas: TCanvas;
begin
  Canvas := (Sender as TPaintBox).Canvas;
  SetFontQuality(Canvas.Font, FontQualities[CheckBox1.Checked]);
  Canvas.TextOut(12, 12, 'Hello, world!');
end;