Sign in Join
Wiki copytemporary

Graphics - Working with TCanvas/it

English · Français · Italiano · Русский

Usare il font di default della GUI

Il font di default si ottiene con il seguente codice:

pascal
SelectObject(Canvas.Handle, GetStockObject(DEFAULT_GUI_FONT));

Disegnare un testo delimitato in larghezza

Usare la routine DrawText due volte, prima con l'opzione DT_CALCRECT e poi senza.
Esempio (Lazarus v1.6 con windows vista):

pascal
..
uses ... windows ...
..
var Image1: TImage;
    TextBox: TRect;
    Text: String;
...
Text:= ...;
// Prima calcoliamo la dimensione del testo, poi lo disegniamo:
TextBox:= Rect(10, 10, Image1.Width - 10, High(Integer));
// questa istruzione ricalcola TextBox.Bottom:
DrawText(Image1.canvas.Handle, PChar(Text), Length(Text),
  TextBox, DT_WORDBREAK or DT_INTERNAL or DT_CALCRECT);
// questa istruzione scrive il testo
DrawText(Image1.Canvas.Handle, PChar(Text), Length(Text),
  TextBox, DT_WORDBREAK or DT_INTERNAL);

Disegnare un testo con bordi netti (non antialiased)

Alcuni widgetsets lo supportano, nel qual caso si usa il seguente codice:

pascal
Canvas.Font.Quality := fqNonAntialiased;

Altri widgetsets come il gtk2 non lo supportano e disegnano sempre antialiased. Di seguito una semplice procedura per disegnare un testo a bordi netti sotto gtk2. Non tiene conto di tutti i casi, ma rende l'idea:

pascal
procedure PaintAliased(Canvas: TCanvas; x,y: integer; const TheText: string);
var
  w,h: integer;
  IntfImg: TLazIntfImage;
  Img: TBitmap;
  dy: Integer;
  dx: Integer;
  col: TFPColor;
  FontColor: TColor;
  c: TColor;
begin
  w:=0;
  h:=0;
  Canvas.GetTextSize(TheText,w,h);
  if (w<=0) or (h<=0) then exit;
  Img:=TBitmap.Create;
  IntfImg:=nil;
  try
    // paint text to a bitmap
    Img.Masked:=true;
    Img.SetSize(w,h);
    Img.Canvas.Brush.Style:=bsSolid;
    Img.Canvas.Brush.Color:=clWhite;
    Img.Canvas.FillRect(0,0,w,h);
    Img.Canvas.Font:=Canvas.Font;
    Img.Canvas.TextOut(0,0,TheText);
    // get memory image
    IntfImg:=Img.CreateIntfImage;
    // replace gray pixels
    FontColor:=ColorToRGB(Canvas.Font.Color);
    for dy:=0 to h-1 do begin
      for dx:=0 to w-1 do begin
        col:=IntfImg.Colors[dx,dy];
        c:=FPColorToTColor(col);
        if c<>FontColor then
          IntfImg.Colors[dx,dy]:=colTransparent;
      end;
    end;
    // create bitmap
    Img.LoadFromIntfImage(IntfImg);
    // paint
    Canvas.Draw(x,y,Img);
  finally
    IntfImg.Free;
    Img.Free;
  end;
end;

From the Free Pascal wiki, page "Graphics - Working with TCanvas/it", as it stood on 2020-02-13 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 3, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.