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

DelphiX 實戰:TDIB.FadeOut 與 FadeIn 淡入淡出效果

     編輯:Delphi

TDIB.FadeOut 與 FadeIn 實現影像的淡出/淡入轉場,以指定步長逐漸調整像素亮度。本文提供載入圖片後按鈕觸發雙向淡化的完整範例。

效果預覽

FadeOut/FadeIn 效果

核心程式碼

unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DIB, StdCtrls;
type
  TForm1 = class(TForm)
    DXPaintBox1: TDXPaintBox;
    Button1: TButton; // 載入圖片
    Button2: TButton; // 淡出
    Button3: TButton; // 淡入
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;
var Form1: TForm1;
implementation {$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
const ImgPath1 = 'C:\Temp\DX.jpg';
begin
  DXPaintBox1.DIB.LoadFromFile(ImgPath1);
  DXPaintBox1.Width := DXPaintBox1.DIB.Width;
  DXPaintBox1.Height := DXPaintBox1.DIB.Height;
  DXPaintBox1.Repaint;
end;

procedure TForm1.Button2Click(Sender: TObject); // FadeOut
begin
  // FadeOut(SrcDIB, Step: Byte)
  DXPaintBox1.DIB.FadeOut(DXPaintBox1.DIB, 127);
  DXPaintBox1.Repaint;
end;

procedure TForm1.Button3Click(Sender: TObject); // FadeIn
begin
  // FadeIn(SrcDIB, Step: Byte)
  DXPaintBox1.DIB.FadeIn(DXPaintBox1.DIB, 127);
  DXPaintBox1.Repaint;
end;
end.

參數說明

FadeOut(SrcDIB: TDIB; Step: Byte)
FadeIn(SrcDIB: TDIB; Step: Byte)
  • SrcDIB:參考原圖(此處為自身)
  • Step (0~255):每次調用的亮度變化量,越大變化越劇烈
  • 範例值 127 為中等步長,約需 2 次完成全黑/全亮

效果原理

  • FadeOut:每像素 RGB 分量向 0 靠攏 Step,漸變全黑
  • FadeIn:每像素 RGB 分量向原圖對應值靠攏 Step,從當前狀態漸變回原圖
  • 需先有原圖參考,通常配合 Assign 保存原圖副本

動畫化實作

var FadingOut: Boolean = True; Step: Byte = 10;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if FadingOut then
    DXPaintBox1.DIB.FadeOut(OriginalDIB, Step)
  else
    DXPaintBox1.DIB.FadeIn(OriginalDIB, Step);
  DXPaintBox1.Repaint;
  // 判斷是否完成(可檢查是否全黑/等於原圖)
end;

應用場景

  • **場景轉場**:關卡切換、選單開關
  • **UI 彈出/隱藏**:對話框、工具提示、選單
  • **受傷/死亡閃紅**:角色受擊時螢幕紅色淡入淡出
  • **載入畫面**:進度條完成後淡出進入遊戲

進階:自訂顏色淡化

內建方法固定向黑/原圖插值。若需淡入特定顏色(如紅色受傷),需自行實作:

procedure FadeToColor(DIB: TDIB; TargetColor: TColor; Step: Byte);
var x, y: Integer; c: TRGBQuad;
begin
  for y := 0 to DIB.Height - 1 do
    for x := 0 to DIB.Width - 1 do begin
      c := DIB.Pixels[x, y];
      c.rgbRed := c.rgbRed + Sign(GetRValue(TargetColor) - c.rgbRed) * Min(Step, Abs(GetRValue(TargetColor) - c.rgbRed));
      c.rgbGreen := c.rgbGreen + Sign(GetGValue(TargetColor) - c.rgbGreen) * Min(Step, Abs(GetGValue(TargetColor) - c.rgbGreen));
      c.rgbBlue := c.rgbBlue + Sign(GetBValue(TargetColor) - c.rgbBlue) * Min(Step, Abs(GetBValue(TargetColor) - c.rgbBlue));
      DIB.Pixels[x, y] := c;
    end;
end;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved