萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Delphi 取得系統支援色彩數 (位元深度) 方法

需求場景

應用程式需根據顯示卡色彩深度 (8-bit/16-bit/24-bit/32-bit) 調整 UI 圖示品質、漸層繪製或直接警告使用者「建議設定 16-bit 以上色彩」。

核心 API 組合

  1. GetDC(0):取得螢幕裝置內容 (DC) 控制代碼。
  2. GetDeviceCaps(DC, BITSPIXEL):取得每像素位元數 (色彩深度)。
  3. GetDeviceCaps(DC, PLANES):取得色盤數 (通常為 1)。
  4. 實際色彩數 = `2 ^ (BITSPIXEL * PLANES)`。
  5. ReleaseDC(0, DC):釋放 DC。

完整函數

function GetSystemColorCount: Longint;
var
  ScreenDC: HDC;
  BitsPixel, Planes: Integer;
begin
  Result := 0;
  ScreenDC := GetDC(0);
  try
    BitsPixel := GetDeviceCaps(ScreenDC, BITSPIXEL);
    Planes    := GetDeviceCaps(ScreenDC, PLANES);
    Result := 1 shl (BitsPixel * Planes);  // 2 的 (BitsPixel * Planes) 次方
  finally
    ReleaseDC(0, ScreenDC);
  end;
end;

呼叫範例

procedure TForm1.Button1Click(Sender: TObject);
var
  ColorCount: Longint;
  DepthStr: string;
begin
  ColorCount := GetSystemColorCount;
  case ColorCount of
    16:       DepthStr := '4-bit (16 色)';
    256:      DepthStr := '8-bit (256 色)';
    65536:    DepthStr := '16-bit (65,536 色 / High Color)';
    16777216: DepthStr := '24-bit (16.7M 色 / True Color)';
    4294967296: DepthStr := '32-bit (True Color + Alpha)';
  else
    DepthStr := Format('%d 色 (未知深度)', [ColorCount]);
  end;
  ShowMessage('目前系統色彩數:' + DepthStr);
end;

現代補充:多螢幕與高 DPI

  • 上述程式碼取得**主螢幕**色彩深度。多螢幕環境下各螢幕可能不同,需使用 `EnumDisplayMonitors` + `GetMonitorInfo` + `GetDC(MonitorHandle)` 分別查詢。
  • Windows 10/11 預設 32-bit 色彩深度,此函數通常回傳 `4294967296` (2^32),實際顯示為 24-bit 色彩 + 8-bit Alpha。
  • 若需支援 Per-Monitor DPI Awareness,專案需加入資訊清單 (Manifest) 宣告 `dpiAware=True/PM`。

相關 GetDeviceCaps 索引常數

常數 意義 典型值
BITSPIXEL 每像素位元數 4, 8, 16, 24, 32
PLANES 色盤數 1
NUMCOLORS 調色盤項目數 (調色盤模式下) 16, 256
HORZRES / VERTRES 螢幕寬/高 (像素) 1920 / 1080
LOGPIXELSX / LOGPIXELSY 水平/垂直 DPI 96, 120, 144...

結語

透過 `GetDeviceCaps` 取得 `BITSPIXEL` 與 `PLANES` 計算色彩數,是 Delphi 經典且可靠的方法。現代環境幾乎皆為 True Color (24/32-bit),但此函數仍適用於相容舊硬體、遠端桌面會話 (可能降為 16-bit) 或自動調整 UI 渲染策略的場景。

copyright © 萬盛學電腦網 all rights reserved