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

MFC 單視圖多繪圖縮放衝突的解決:採用單例模式統一繪圖邏輯與坐標變換

     編輯:程式設計疑難解答

問題現象

在一個 View 中加載多個繪圖對象,各自處理縮放邏輯導致座標映射衝突、重繪錯位。

解決方案:單例繪圖管理器


class DrawManager {
public:
    static DrawManager& Instance() {
        static DrawManager inst;
        return inst;
    }
    void RegisterDrawer(IDrawer* drawer) { drawers_.push_back(drawer); }
    void UnregisterDrawer(IDrawer* drawer) { 
        drawers_.erase(std::remove(drawers_.begin(), drawers_.end(), drawer), drawers_.end());
    }
    void OnDraw(CDC* pDC, const CRect& clientRect) {
        for (auto d : drawers_) d->Draw(pDC, clientRect, GetTransform());
    }
    void SetZoom(double factor, CPoint center) { /* 更新統一變換矩陣 */ }
    Matrix GetTransform() const { return transform_; }
private:
    DrawManager() {}
    std::vector drawers_;
    Matrix transform_;
};

接入方式

  • 各繪圖對象實現 IDrawer::Draw(CDC*, CRect, Matrix),使用統一變換矩陣繪制。
  • View 的 OnDraw 僅調用 DrawManager::Instance().OnDraw(pDC, rect)。
  • 縮放/平移操作調用 DrawManager::Instance().SetZoom(...),然後 Invalidate()。

優勢

  • 單一真實源:座標變換、視口範圍、圖層順序集中管理。
  • 避免多對象獨立計算導致的不一致。
  • 易於擴展:添加圖層控制、選中高亮、導出圖片等功能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved