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

再學GDI+[58]: 路徑資料序列化 - 保存與讀取路徑點陣列至文字檔

     編輯:Delphi

前言

路徑資料持久化是向量圖形編輯器、CAD 系統的基礎功能。本文示範如何將 TGPGraphicsPath 的點座標陣列與點類型陣列序列化為文字檔,再完整還原重建路徑。

序列化核心步驟

  1. GetPointCount 取得點數
  2. 配置動態陣列 points: array of TGPPoint, types: array of Byte
  3. GetPathPoints、GetPathTypes 填充陣列
  4. 格式化為 "X,Y,Type" 文字行,存入 TStringList → SaveToFile

反序列化還原步驟

  1. LoadFromFile 讀取文字檔
  2. 逐行解析 X, Y, Type 重建陣列
  3. path.Reset; path.Free 釋放舊路徑
  4. TGPGraphicsPath.Create(PGPPoint(points), PByte(types), count) 重建新路徑

完整雙向實作

const FilePath = 'c:\temp\path.txt';

procedure TForm1.Button1Click(Sender: TObject);  {保存}
var
  points: array of TGPPoint;
  types: array of Byte;
  List: TStringList;
  i: Integer;
begin
  SetLength(points, path.GetPointCount);
  SetLength(types, path.GetPointCount);
  path.GetPathPoints(PGPPoint(points), Length(points));
  path.GetPathTypes(PByte(types), Length(types));
  List := TStringList.Create;
  for i := 0 to Length(points) - 1 do
    List.Add(Format('%d,%d,%d', [points[i].X, points[i].Y, types[i]]));
  List.SaveToFile(FilePath);
  List.Free;
  Caption := FilePath;
end;

procedure TForm1.Button2Click(Sender: TObject);  {讀取}
var
  points: array of TGPPoint;
  types: array of Byte;
  List1, List2: TStringList;
  i: Integer;
begin
  List1 := TStringList.Create;
  List2 := TStringList.Create;
  if not FileExists(FilePath) then Exit;
  List1.LoadFromFile(FilePath);
  SetLength(points, List1.Count);
  SetLength(types, List1.Count);
  for i := 0 to List1.Count - 1 do begin
    if List1[i] = '' then Break;
    List2.CommaText := List1[i];
    points[i].X := StrToIntDef(List2[0], 0);
    points[i].Y := StrToIntDef(List2[1], 0);
    types[i] := StrToIntDef(List2[2], 0);
  end;
  path.Reset; path.Free;
  path := TGPGraphicsPath.Create(PGPPoint(points), PByte(types), List1.Count);
  p.SetColor(aclRed);  {改色驗證}
  Repaint;
  List1.Free; List2.Free;
end;

執行效果預覽

路徑儲存讀取效果

進階補充:TPathData 簡化版

GDI+ 也提供 TPathData 類別封裝點/類型陣列,操作更簡潔:

var PathData: TPathData;
PathData := TPathData.Create;
path.GetPathData(PathData);  {一次取得 Points、Types、Count}
{直接存取 PathData.Points^, PathData.Types^, PathData.Count}
PathData.Free;

關鍵技術點

  • 點類型保真:Type 陣列記錄 Start/Line/Bezier/Close 等關鍵資訊,還原時必須保留
  • 動態陣列管理:SetLength/FreeMem 配對使用,避免記憶體洩漏
  • 檔案格式:純文字 CSV 格式,人類可讀、跨平台相容
  • 路徑重建:建構子 Create(points, types, count) 完整還原幾何與拓撲

表單定義檔

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 147
  ClientWidth = 224
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  OnDestroy = FormDestroy
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton ... {保存/讀取兩按鈕}
end
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved