首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# GDI+ 影像淡入淡出效果:ColorMatrix 透明度動畫完整實作

     編輯:關於C#

原理說明

利用 ImageAttributes.SetColorMatrix 設定 5x5 色彩轉換矩陣,調整矩陣對角線元素(M33 對應 Alpha 通道)從 0→1(淡入)或 1→0(淡出),搭配 Graphics.DrawImage 繪製每一幀,即可實現淡入淡出動畫。

核心矩陣結構

[ R  0  0  0  0 ]   // Red
[ 0  G  0  0  0 ]   // Green
[ 0  0  B  0  0 ]   // Blue
[ 0  0  0  A  0 ]   // Alpha (M33)
[ 0  0  0  0  1 ]   // W (M44, 固定 1)

淡入:A 從 0 遞增至 1
淡出:A 從 1 遞減至 0

完整 WinForm 實作

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public partial class Form1 : Form
{
    private Bitmap _sourceImage;

    public Form1()
    {
        InitializeComponent();
        _sourceImage = new Bitmap("sample.jpg"); // 載入測試圖片
    }

    // === 淡入動畫 ===
    private async void btnFadeIn_Click(object sender, EventArgs e)
    {
        await FadeAnimation(0f, 1f, 0.02f, 20); // 從 0 到 1,步進 0.02,延遲 20ms
    }

    // === 淡出動畫 ===
    private async void btnFadeOut_Click(object sender, EventArgs e)
    {
        await FadeAnimation(1f, 0f, -0.02f, 20);
    }

    // === 通用淡入淡出核心邏輯 ===
    private Task FadeAnimation(float startAlpha, float endAlpha, float step, int delayMs)
    {
        return Task.Run(() =>
        {
            using (Graphics g = panel1.CreateGraphics())
            {
                g.Clear(Color.Gray); // 背景色

                var attributes = new ImageAttributes();
                var matrix = new ColorMatrix
                {
                    Matrix33 = startAlpha, // 初始 Alpha
                    Matrix44 = 1f
                };

                float alpha = startAlpha;
                bool increasing = step > 0;

                while (increasing ? alpha <= endAlpha : alpha >= endAlpha)
                {
                    matrix.Matrix33 = alpha;
                    attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                    // 在 UI 執行緒繪圖
                    this.Invoke((Action)(() =>
                    {
                        g.DrawImage(_sourceImage,
                            new Rectangle(0, 0, _sourceImage.Width, _sourceImage.Height),
                            0, 0, _sourceImage.Width, _sourceImage.Height,
                            GraphicsUnit.Pixel, attributes);
                    }));

                    alpha += step;
                    Thread.Sleep(delayMs);
                }
            }
        });
    }
}

關鍵類別與方法對照

類別/方法用途
ColorMatrix5x5 仿射轉換矩陣,控制 RGBA 縮放與平移
ImageAttributes.SetColorMatrix將矩陣套用至後續 DrawImage 操作
Graphics.DrawImage(..., ImageAttributes)依指定屬性繪製影像
ColorMatrixFlag.Default套用至整個影像(含灰階調整)
ColorAdjustType.Bitmap指定調整目標為點陣圖

效能優化建議

  1. 雙緩衝:panel1.DoubleBuffered = true 減少閃爍
  2. 離螢幕繪圖:先繪製至 Bitmap 再一次 DrawImage 至螢幕
  3. 非同步/Task:避免阻塞 UI 執行緒,範例已使用 Task.Run + Invoke
  4. 硬體加速:WPF/UWP 專案建議用 Opacity 動畫或 Effect,效能遠優於 GDI+

常見問題 FAQ

問題原因與解決
動畫卡頓UI 執行緒被 Sleep 阻塞 → 改用 Task/Timer/async-await
影像邊緣鋸齒g.InterpolationMode = InterpolationMode.HighQualityBicubic
背景殘影每幀先 g.Clear 或繪製背景圖
透明背景變黑來源影像需為 32bppArgb,或矩陣 M44=1, M33 控制 Alpha

擴充:自訂色彩特效

修改矩陣其他元素可實現:

  • 灰階:R=G=B=0.299/0.587/0.114 加權
  • 負片:對角線 -1,平移 +1
  • 飽和度:調整 R/G/B 對角線係數
  • 色相旋轉:3x3 子矩陣套用旋轉變換

參考:MSDN ColorMatrix 文件、GDI+ 影像處理教學

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved