"Extra" text on TCanvas?

To my surprise, I found that translating text to TCanvas multiple times is "additive." I understand that the Canvas.Brush.Style:=bsClear parameter is the cause of the problem, but I really need to render the text transparently and repeatedly (for example, in the OnPaint event). After that, the text does not look very good.

How can i avoid this?

Here is a sample code; you can see the effect if you make a few clicks on TButton called btn1 .

 procedure TForm1.btn1Click(Sender: TObject); begin Form1.Canvas.Brush.Style:=bsClear; //if you omit this, everything is OK. Form1.Canvas.Font.Color:=clRed; Form1.Canvas.Font.Name:='Times new Roman'; Form1.Canvas.Font.Style:=[fsBold]; Form1.Canvas.Font.Size:=12; Form1.Canvas.TextOut(50,50,'www.stackoverflow.com'); end; 
+4
source share
2 answers

This is because GDI applies some anti-aliasing when drawing text to make the text look better. This causes some background pixels outside the drawn text to be red / reddish next to the text. The next time you draw text, if you do not clear the background, smoothing causes these reddish pixels to become redder.

You either clear the background like Arioch ' specified in it, or if you really need to make the text transparent and multiple times, you can turn off anti-aliasing.

TOndrej provided a nice feature in this answer to indicate the quality of the text output. Using it, the code becomes:

 begin Form1.Canvas.Brush.Style:=bsClear; Form1.Canvas.Font.Color:=clRed; Form1.Canvas.Font.Name:='Times new Roman'; Form1.Canvas.Font.Style:=[fsBold]; Form1.Canvas.Font.Size:=12; SetFontQuality(Form1.Canvas.Font, NONANTIALIASED_QUALITY); // <-- Form1.Canvas.TextOut(50,50,'www.stackoverflow.com'); end; 
+7
source

You must clear the background before rendering.

If such messages / events are not displayed by the control, you need to remember the last displayed text TRect (function TCanvas.TextExtent or the like) and clear it before displaying the next text.

It is also sometimes possible and simpler (although this is a kind of "dirty and ugly" solution) to keep the transparent TLabel floating above the canvas in the right place and, if necessary, change its title.

+3
source

Source: https://habr.com/ru/post/1434778/


All Articles