漸變背景能顯著提升 UI 視覺質感。本文演示在 C++Builder 中通過 OnPaint 事件,利用 RGB 宏與線性插值算法,逐行繪製垂直方向顏色漸變,並支持運行時通過 TColorDialog 動態選擇起止顏色。
設窗體寬度 W,起始色 Cstart = (Rs, Gs, Bs),結束色 Cend = (Re, Ge, Be)。第 x 條垂直線 (0 ≤ x < W) 的顏色:
R(x) = Rs + (Re - Rs) * x / W G(x) = Gs + (Ge - Gs) * x / W B(x) = Bs + (Be - Bs) * x / W
private:
TColor StartColor, EndColor; // 起止顏色
void __fastcall TForm1::FormCreate(TObject *Sender) {
if (ColorDialog1->Execute()) StartColor = ColorDialog1->Color;
if (ColorDialog1->Execute()) EndColor = ColorDialog1->Color;
}
void __fastcall TForm1::FormPaint(TObject *Sender) {
float w = Width;
int rs = GetRValue(StartColor), gs = GetGValue(StartColor), bs = GetBValue(StartColor);
int re = GetRValue(EndColor), ge = GetGValue(EndColor), be = GetBValue(EndColor);
float dr = (re - rs) / w;
float dg = (ge - gs) / w;
float db = (be - bs) / w;
for (int x = 0; x < Width; ++x) {
Canvas->Pen->Color = TColor(RGB(
rs + int(dr * x),
gs + int(dg * x),
bs + int(db * x)
));
Canvas->MoveTo(x, 0);
Canvas->LineTo(x, Height);
}
}
| 模式 | 核心修改 | 效果 |
|---|---|---|
| 水平漸變 (左→右) | 外層循環 y,MoveTo(0,y) LineTo(Width,y) | 左右顏色過渡 |
| 對角漸變 | 插值參數 t = (x+y)/(W+H) | 左上→右下 |
| 圓形漸變 | 同心圓半徑遞減,顏色按半徑插值 | 中心向四周擴散 |
| 多色漸變 | 定義色標數組,分段線性插值 | 彩虹/多階過渡 |
TBitmap 上繪製完畢再 Canvas->Draw(0,0,bmp),避免閃爍並加速;Resize 或顏色改變時重繪;GradientFill API** (Windows 2000+):系統級硬件加速漸變,代碼更簡潔;TBrush.Gradient** 跨平台無痛實現。RGB 宏參數須為 0-255 整數,浮點插值結果需 int() 截斷;GetRValue/G/BValue 參數為 TColor (實為 DWORD),高位若非 0 會干擾,確保顏色來自 ColorDialog 或 clRed 等常量;OnPaint 中避免耗時操作,否則導致界面卡頓。掌握像素級繪製基礎,即可構建任意自定義視覺效果,為 C++Builder 應用賦予現代化 UI 風格。