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

C# 圖片淡入效果實現:ColorMatrix 動畫詳解

     編輯:關於C語言

利用 `ImageAttributes.SetColorMatrix` 動態調整顏色矩陣主對角線值(0→1),實現平滑淡入動畫。

核心代碼

private void btnFadeIn_Click(object sender, EventArgs e) {
    Graphics g = panel1.CreateGraphics();
    g.Clear(Color.Gray);
    int w = MyBitmap.Width, h = MyBitmap.Height;

    ImageAttributes attr = new ImageAttributes();
    ColorMatrix cm = new ColorMatrix();
    // 初始化為零矩陣,保留 Alpha 通道
    cm.Matrix33 = cm.Matrix44 = 1f;

    for (float c = 0f; c < 1f; c += 0.02f) {
        cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = cm.Matrix33 = c;
        attr.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        g.DrawImage(MyBitmap, new Rectangle(0, 0, w, h), 0, 0, w, h, GraphicsUnit.Pixel, attr);
        Thread.Sleep(20); // 控制幀率
    }
}

原理解析

  • `ColorMatrix` 5x5 矩陣控制 RGBA 變換,主對角線 `Matrix00/11/22` 對應 RGB 飽和度
  • 從 0 遞增到 1,像素顏色分量逐漸恢復,視覺上呈現淡入
  • `Matrix33`(Alpha)與 `Matrix44`(平移分量)通常保持 1

優化建議

  • 使用 `Timer` 或 `async/await` 替代 `Thread.Sleep` 避免阻塞 UI 執行緒
  • 雙緩衝繪圖減少閃爍
  • 釋放 `Graphics`、`ImageAttributes` 等非托管資源
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved