首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

再學GDI+[44]: 文字字體選擇 - TGPFontFamily 系統字體列舉與即時預覽

     編輯:Delphi

前言

TGPFontFamily 封裝字體家族資訊。本文示範如何列舉系統安裝字體(排除 @ 開頭的垂直字體),透過 ListBox 即時切換預覽,並顯示字體實際繪製高度。

字體列舉與預覽實作

var FontName: string = '宋體';

procedure TForm1.FormCreate(Sender: TObject);
var str: string;
begin
  ListBox1.Align := alRight;
  for str in Screen.Fonts do
    if str[1] <> '@' then  {排除垂直字體}
      ListBox1.Items.Add(str);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  g: TGPGraphics;
  b: TGPBrush;
  font: TGPFont;
  fontFamily: TGPFontFamily;
begin
  g := TGPGraphics.Create(Canvas.Handle);
  b := TGPSolidBrush.Create(aclRed);
  fontFamily := TGPFontFamily.Create(FontName);
  font := TGPFont.Create(fontFamily, 48, FontStyleBold);
  g.DrawString('Delphi', -1, font, MakePoint(5.0, 20.0), b);
  Caption := Format('Height: %.2f', [font.GetHeight(g)]);  {顯示實際像素高度}
  fontFamily.Free; font.Free; b.Free; g.Free;
end;

procedure TForm1.ListBox1Click(Sender: TObject);
begin
  FontName := ListBox1.Items[ListBox1.ItemIndex];
  Repaint;
end;

執行效果預覽

字體選擇預覽

關鍵技術點

  • Screen.Fonts vs GDI+ 字體集合:VCL 列舉簡單但含垂直字體;GDI+ TGPInstalledFontCollection 更純粹(見第 43 篇)
  • 字體回退:指定字體不存在時 GDI+ 自動回退,不會報錯
  • GetHeight:回傳指定 Graphics 設備下的實際像素高度,受 DPI 影響
  • FontStyleBold:GDI+ 模擬粗體,非真實字體粗體變體

表單定義檔

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 126
  ClientWidth = 375
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
  object ListBox1: TListBox ... {右側字體列表}
end
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved