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

CChart 入門教程第 5 課:批量繪製多曲線、圖例、座標軸與網格——構建工程級儀表盤

     編輯:關於C語言

痛點解決

第 1 課用 AddPoint2D 逐點添加,數據量大時極其低效。本課掌握 AddCurve 批量添加、多曲線管理、圖例/座標軸/網格完整配置。

核心 API:AddCurve

int AddCurve(double* pX, double* pY, int nLen, int nPlotIndex = 0);
  • pX/pY:雙精度陣列,長度 nLen。
  • nPlotIndex:子視圖索引(分裂/分層視圖用),默認 0。
  • 返回值:曲線唯一 ID(身份證),不隨排序/插入/刪除變化,後續操作(刪除、屬性修改)必須用 ID。

實戰:繪製正弦/餘弦雙曲線

1. 準備數據陣列

#include 
case WM_CREATE:
    chartWnd.Attach(hWnd, kTypeXY);
    {
        double pX[360], pY[360];
        const double PI = 3.1415926536;
        // 曲線 1:y = 5 sin(3x)
        for (int i = 0; i < 360; ++i) {
            pX[i] = i;
            pY[i] = 5.0 * sin(i * 2.0 * PI / 360.0 * 3.0);
        }
        int id1 = chartWnd.GetChart()->AddCurve(pX, pY, 360);
        // 曲線 2:y = 2 cos(3x)
        for (int i = 0; i < 360; ++i) {
            pX[i] = i;
            pY[i] = 2.0 * cos(i * 2.0 * PI / 360.0 * 3.0);
        }
        int id2 = chartWnd.GetChart()->AddCurve(pX, pY, 360);
    }
    chartWnd.GetChart()->SetTitle(_T("CChart 批量繪製多曲線"));
    break;

運行效果

單曲線:

單曲線

雙曲線:

雙曲線

進階配置:圖例、座標軸標題、背景網格

// 顯示圖例
chartWnd.GetChart()->SetUseLegend(true);

// 設置曲線名稱(圖例顯示)
chartWnd.GetChart()->SetDataTitle(_T("王菲"), 0); // 索引 0 = 第 1 條曲線
chartWnd.GetChart()->SetDataTitle(_T("李亞鵬"), 1); // 索引 1 = 第 2 條曲線

// 座標軸標題
chartWnd.GetChart()->SetAxisTitle(_T("橫軸 (度)"), 1); // 1 = 底部 X 軸
chartWnd.GetChart()->SetAxisTitle(_T("縱軸 (振幅)"), 0); // 0 = 左側 Y 軸
// 座標軸位置常數:0=左, 1=下, 2=右, 3=上

// 背景網格與顏色
chartWnd.GetChart()->SetGridLine(true, true, true, true); // 主橫/主豎/次橫/次豎
chartWnd.GetChart()->SetBkgndColor(RGB(224, 224, 224));  // 淺灰背景

最終效果

完整儀表盤

API 速查表

方法簽名說明
AddCurveint AddCurve(double*, double*, int, int=0)批量添加曲線,返回唯一 ID
SetDataTitlevoid SetDataTitle(const TCHAR*, int nDataIndex, int nPlotIndex=0)設置曲線圖例名稱
SetAxisTitlevoid SetAxisTitle(const TCHAR*, int location, int nPlotIndex=0)location: 0左/1下/2右/3上
SetGridLinevoid SetGridLine(bool MajorH, bool MajorV, bool MinorH, bool MinorV, int nPlotIndex=0)主/次網格橫豎獨立控制
SetBkgndColorvoid SetBkgndColor(COLORREF, int nPlotIndex=0)繪圖區背景色
SetUseLegendvoid SetUseLegend(bool)顯示/隱藏圖例

曲線 ID 的重要性

  • 曲線內部以 std::vector 存儲,插入/刪除/排序會改變下標。
  • ID 類似身份證,全生命週期不變,安全引用。
  • 後續 RemoveCurve(id)、SetCurveStyle(id, ...) 均需 ID。

總結

掌握 AddCurve + 圖例/軸/網格配置,即可構建專業級實時監控儀表盤。下一課將講解實時動態更新與大數據量優化策略。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved