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

再學GDI+[70]: 路徑漸層筆刷進階混色控制 - SetBlend 精準調配顏色位置與權重

     編輯:Delphi

前言

SetBlend 方法提供了對路徑漸層筆刷最精細的顏色混合控制,允許開發者為每個環繞顏色指定混合因子與位置。本文透過六個軌條條即時調整三組顏色的混合參數,展示如何打造客製化漸層效果。

SetBlend 參數詳解

procedure SetBlend(blendFactors, positions: PSingle; count: Integer);
  • blendFactors:混合因子陣列(0.0~1.0),決定該顏色在混合中的權重
  • positions:位置陣列(0.0~1.0),對應路徑從中心到邊緣的相對距離
  • count:陣列元素個數,必須與 SetSurroundColors 設定的顏色數一致

六軌條即時控制介面

軌條控制參數對應顏色索引範圍
TrackBar1blendFactors[0]紅色 (aclRed)0.0~1.0
TrackBar2blendFactors[1]綠色 (aclGreen)0.0~1.0
TrackBar3blendFactors[2]黃色 (aclYellow)0.0~1.0
TrackBar4positions[0]紅色位置0.0~1.0
TrackBar5positions[1]綠色位置0.0~1.0
TrackBar6positions[2]黃色位置0.0~1.0

核心實作程式碼

procedure TForm1.FormPaint(Sender: TObject);
const
  pts: array[0..2] of TGPPoint = ((X:120; Y:10), (X:40; Y:140), (X:200; Y:140));
  colors: array[0..2] of TGPColor = (aclRed, aclGreen, aclYellow);
var
  g: TGPGraphics;
  path: TGPGraphicsPath;
  pb: TGPPathGradientBrush;
  blendFactors: array[0..2] of Single;
  pos: array[0..2] of Single;
  num: Integer;
begin
  g := TGPGraphics.Create(Canvas.Handle);
  path := TGPGraphicsPath.Create;
  path.AddPolygon(PGPPoint(@pts), Length(pts));
  pb := TGPPathGradientBrush.Create(path);
  num := Length(colors);
  pb.SetSurroundColors(@colors, num);  {必須先設定環繞顏色}
  
  {從軌條讀取參數}
  blendFactors[0] := TrackBar1.Position / 10;
  blendFactors[1] := TrackBar2.Position / 10;
  blendFactors[2] := TrackBar3.Position / 10;
  pos[0] := TrackBar4.Position / 10;
  pos[1] := TrackBar5.Position / 10;
  pos[2] := TrackBar6.Position / 10;
  
  {套用混合設定}
  pb.SetBlend(@blendFactors, PSingle(@pos), Length(blendFactors));
  
  g.FillPath(pb, path);
  pb.Free; path.Free; g.Free;
end;

執行效果預覽

SetBlend 混色效果

關鍵技術重點

  1. 前置條件:必須先呼叫 SetSurroundColors 定義顏色陣列,SetBlend 才會生效
  2. 位置遞增:positions 陣列數值必須遞增(0.0 到 1.0),否則結果不可預期
  3. 因子疊加:混合因子不需正規化,GDI+ 內部會自動處理權重分配
  4. 動態調整:搭配 UI 控制項即時修改參數,是設計漸層編輯器的核心技術

表單定義檔

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 222
  ClientWidth = 242
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
  object TrackBar1: TTrackBar ... {六個 TrackBar 定義略}
end
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved