Canvas.TextOut 是最基礎的文字輸出函數,配合 TextWidth/TextHeight 度量,能實現字元級的精確定位控制。本文通過逐字繪製古詩範例,展示如何計算每個字元的寬高並實現等寬/非等寬字體的精確排版。
procedure TextOut(X, Y: Integer; const Text: string);
function TextWidth(const Text: string): Integer;
function TextHeight(const Text: string): Integer;
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const
Arr: array[0..3] of WideString = (
'白日依山盡',
'黃河入海流',
'欲窮千裡目',
'更上一層樓'
);
A = 20; // 橫向間距
B = 20; // 縱向間距
var
S: string;
X, Y: Integer;
I, J: Integer;
begin
X := 20;
Y := 20;
for I := 0 to Length(Arr) - 1 do
begin
// 注意:WideString 索引從 1 開始,Length 返回字元數
for J := 1 to Length(Arr[I]) do
begin
S := Arr[I][J]; // 取單字元
Canvas.TextOut(X, Y, S); // 繪製
X := X + Canvas.TextWidth(S) + A; // 移動到下一字元位置
end;
X := 20; // 換行回行首
Y := Y + Canvas.TextHeight(S) + B; // 移動到下一行
end;
end;
end.
WideString 索引從 1 開始 (同 string)Length(WideString) 返回 字元數 (非位元組數)Arr[I][J] 返回 WideChar,隱式轉為 string 給 TextOut| 函數 | 返回值 | 受 Font 影響 | 典型用途 |
|---|---|---|---|
| TextWidth | 字串像素寬度 | 是 | 水平定位、換行判斷 |
| TextHeight | 字串像素高度 (含行距) | 是 | 垂直定位、行高計算 |
| TextExtent | TSize(cx, cy) | 是 | 一次獲取寬高 |