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

再學GDI+[69]: 路徑漸層筆刷雙雄對決 - SetInterpolationColors vs SetSurroundColors 差異深度解析

     編輯:Delphi

前言

路徑漸層筆刷提供兩種設定顏色的方法:SetSurroundColors 與 SetInterpolationColors。雖然都能建立漸層,但運作機制、適用場景、參數需求截然不同。本文透過四連畫面並排比較,徹底釐清兩者差異。

核心差異對照表

特性SetSurroundColorsSetInterpolationColors
參數結構顏色陣列 + 個數顏色陣列 + 位置陣列 + 個數
位置控制自動平均分佈(無法自訂)精確指定每個顏色的相對位置 (0.0~1.0)
中心色處理預設白色,可用 SetCenterColor 修改不使用中心色,直接由插值定義整個漸層
路徑建立方式影響受路徑點數與順序影響大僅受路徑形狀影響,不受點數影響
適用場景簡單均勻漸層、多邊形頂點對應顏色精細漸層控制、非線性色彩變化、複雜路徑

四連畫面比較實作

程式在單一視窗中並排繪製四種情境:

  1. 橢圓路徑 + SetInterpolationColors - 精確控制位置
  2. 橢圓路徑 + SetSurroundColors - 自動平均分佈
  3. 提取路徑點建立筆刷 + SetSurroundColors - 需手動設定中心色
  4. 提取路徑點建立筆刷 + SetInterpolationColors - 純插值模式

關鍵程式碼片段

procedure TForm1.FormPaint(Sender: TObject);
const
  colors: array[0..3] of TGPColor = (aclRed, aclYellow, aclGreen, aclBlue);
  pos: array[0..3] of Single = (0.0, 0.2, 0.6, 1.0);  {兩端必須為 0 和 1}
var
  g: TGPGraphics;
  path: TGPGraphicsPath;
  pb: TGPPathGradientBrush;
  num: Integer;
  pts: array of TGPPoint;
begin
  g := TGPGraphics.Create(Canvas.Handle);
  path := TGPGraphicsPath.Create;
  
  {第 1 組:橢圓路徑 + SetInterpolationColors}
  path.AddEllipse(MakeRect(10,10,150,150));
  pb := TGPPathGradientBrush.Create(path);
  pb.SetInterpolationColors(@colors, @pos, Length(pos));
  g.FillPath(pb, path);
  
  {第 2 組:同路徑 + SetSurroundColors}
  pb.Free;
  pb := TGPPathGradientBrush.Create(path);
  num := Length(pos);
  pb.SetSurroundColors(@colors, num);
  g.TranslateTransform(160, 0);
  g.FillPath(pb, path);
  
  {第 3 組:提取路徑點建立 + SetSurroundColors}
  SetLength(pts, path.GetPointCount);
  path.GetPathPoints(PGPPoint(pts), Length(pts));
  pb.Free;
  pb := TGPPathGradientBrush.Create(PGPPoint(pts), Length(pts));
  pb.SetCenterColor(aclWhite);  {此模式必須設定中心色}
  num := Length(colors);
  pb.SetSurroundColors(@colors, num);
  g.TranslateTransform(160, 0);
  g.FillPath(pb, path);
  
  {第 4 組:提取路徑點建立 + SetInterpolationColors}
  pb.Free;
  pb := TGPPathGradientBrush.Create(PGPPoint(pts), Length(pts));
  pb.SetInterpolationColors(@colors, @pos, Length(pos));
  g.TranslateTransform(160, 0);
  g.FillPath(pb, path);
  
  {清理資源}
  pb.Free; path.Free; g.Free;
end;

執行效果預覽

四種模式並排比較

實戰選擇指南

  • 選 SetSurroundColors 當:建立多邊形頂點顏色插值、需要中心色控制、簡單均勻漸層
  • 選 SetInterpolationColors 當:需要精確控制色帶位置、非線性漸層、複雜路徑形狀、不想處理中心色
  • 路徑建立方式:直接用幾何路徑建立筆刷較穩定;提取點陣列建立則適用於動態生成的路徑

表單定義檔

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 169
  ClientWidth = 649
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
end
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved