首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 5 面向對象繪圖庫構建:從像素操作到圖形物件模型

     編輯:PHP 綜合知識

兩類繪圖模式對比

繪圖程式 (Pixel-based)制圖程式 (Object-based)
像素級控制 (Photoshop)物件組合 (Illustrator/Visio)
適合照片編輯、特效適合商業圖表、流程圖、架構圖
GD 庫原生 API 屬此類需自行封裝物件層

面向對象圖形庫設計目標

  1. 從基本操作轉向物件:提供 Line、Rectangle、Oval 等物件,支援群組與複合物件
  2. Z-值排序:物件擁有 z-index,值大者後繪製,疊加在上層
  3. 多輸出格式支援:同一物件模型可輸出 PNG、JPEG、SVG、Flash 等

核心類別架構 (PHP 5 OOP)

<?php
abstract class Shape {
    protected $zIndex = 0;
    protected $color = '000000';
    protected $visible = true;

    public function setZIndex($z) { $this->zIndex = $z; return $this; }
    public function getZIndex() { return $this->zIndex; }
    public function setColor($c) { $this->color = $c; return $this; }
    abstract public function render($canvas); // $canvas 為 GD 資源或 SVG 寫入器
}

class Line extends Shape {
    private $x1, $y1, $x2, $y2;
    public function __construct($x1, $y1, $x2, $y2) { ... }
    public function render($canvas) {
        imageline($canvas, $this->x1, $this->y1, $this->x2, $this->y2, $this->resolveColor($canvas));
    }
}

class Rectangle extends Shape {
    private $x, $y, $w, $h, $filled = false;
    public function render($canvas) {
        $func = $this->filled ? 'imagefilledrectangle' : 'imagerectangle';
        $func($canvas, $this->x, $this->y, $this->x+$this->w, $this->y+$this->h, $this->resolveColor($canvas));
    }
}

class Group extends Shape {
    private $shapes = [];
    public function add(Shape $s) { $this->shapes[] = $s; return $this; }
    public function render($canvas) {
        // 依 z-index 排序後依序繪製
        usort($this->shapes, fn($a,$b) => $a->getZIndex() <=> $b->getZIndex());
        foreach ($this->shapes as $s) $s->render($canvas);
    }
}

// 使用範例
$canvas = imagecreatetruecolor(800, 600);
$group = new Group();
$group->add(new Rectangle(10,10,100,50)->setColor('FF0000')->setZIndex(1))
      ->add(new Line(0,0,800,600)->setColor('0000FF')->setZIndex(2))
      ->add(new Oval(200,200,50,30)->setColor('00FF00')->setZIndex(3));
$group->render($canvas);
imagepng($canvas, 'output.png');
?>

關鍵優勢

  • 程式碼可讀性:$rect->setColor('red')->setZIndex(5) 鏈式呼叫直觀
  • 維護性:修改形狀屬性只需調用方法,無需記憶 GD 函數參數順序
  • 擴展性:新增 SVGRenderer 實作 render() 即可輸出 SVG,業務邏輯不變
  • 分組管理:Group 物件遞歸渲染,支援複雜場景樹

PHP 5 OOP 特性應用

  • abstract 定義介面契約
  • protected 封裝內部狀態
  • 型別提示 Shape $s 確保群組只接受形狀物件
  • __construct 強制初始化必要屬性
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved