ColorMatrix 5x5 矩陣控制 RGBA 通道縮放與平移。對角線元素 (0,0)(1,1)(2,2)(3,3) 分別控制 R/G/B/A 縮放。從 1.0 遞減至 0 達成淡出。
private void btnFadeOut_Click(object sender, EventArgs e)
{
Graphics g = panel1.CreateGraphics();
g.Clear(Color.Gray);
int w = MyBitmap.Width, h = MyBitmap.Height;
var attrs = new ImageAttributes();
var matrix = new ColorMatrix
{
Matrix33 = 1, // Alpha 通道預設 1
Matrix44 = 1 // W 分量
};
float factor = 1.0f;
while (factor > 0)
{
matrix.Matrix00 = matrix.Matrix11 = matrix.Matrix22 = matrix.Matrix33 = factor;
attrs.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(MyBitmap, new Rectangle(0, 0, w, h), 0, 0, w, h, GraphicsUnit.Pixel, attrs);
Thread.Sleep(20);
factor -= 0.01f;
}
}
[ R' ] [ M00 M01 M02 M03 M04 ] [ R ] [ G' ] = [ M10 M11 M12 M13 M14 ] [ G ] [ B' ] [ M20 M21 M22 M23 M24 ] [ B ] [ A' ] [ M30 M31 M32 M33 M34 ] [ A ] [ 1 ] [ M40 M41 M42 M43 M44 ] [ 1 ]
Matrix00/11/22:R/G/B 縮放(0~1)Matrix33:Alpha 縮放(0~1,透明度)Matrix44:齊次座標分量(固定 1)見第 4 部分:因子從 0 增加到 1 為淡入,1 減少到 0 為淡出。