利用 flash.filters.ColorMatrixFilter 可在不修改原始圖片像素的情況下,即時將顯示物件轉為灰度(黑白)顯示,並可結合滑鼠事件實現「懸停顯色、移出變灰」的互動效果。代碼極簡,效能極佳。
import flash.filters.ColorMatrixFilter;
// 灰度轉換矩陣(標準亮度加權:R*0.3086 + G*0.6094 + B*0.0820)
// 此處採用簡化版:R/G/B 各通道取 0.5, 0.5, 0.082 權重混合
var matrix:Array = [
0.5, 0.5, 0.082, 0, 0, // R' = 0.5R + 0.5G + 0.082B
0.5, 0.5, 0.082, 0, 0, // G' = 同上
0.5, 0.5, 0.082, 0, 0, // B' = 同上
0, 0, 0, 1, 0 // A' = A
];
var colorMat:ColorMatrixFilter = new ColorMatrixFilter(matrix);
// 目標顯示物件(假設實例名 image_mc)
image_mc.filters = [colorMat]; // 預設灰度顯示
// 滑鼠互動:移入顯色、移出變灰
image_mc.addEventListener(MouseEvent.MOUSE_OVER, over);
image_mc.addEventListener(MouseEvent.MOUSE_OUT, out);
function over(e:MouseEvent):void {
image_mc.filters = []; // 移除濾鏡恢復原色
}
function out(e:MouseEvent):void {
image_mc.filters = [colorMat]; // 重新套用灰度濾鏡
}
ColorMatrixFilter 接受 20 個元素的陣列(4×5 矩陣),對每像素的 RGBA 進行線性變換:
[ R' ] [ a0 a1 a2 a3 a4 ] [ R ] [ G' ] = [ a5 a6 a7 a8 a9 ] [ G ] [ B' ] [ a10 a11 a12 a13 a14 ] [ B ] [ A' ] [ a15 a16 a17 a18 a19 ] [ A ]
上述矩陣將 R/G/B 三通道均設為相同的線性組合(0.5R+0.5G+0.082B),使輸出像素 R'=G'=B',即為灰度值。係數 0.5/0.5/0.082 近似人眼對 RGB 亮度感知權重(標準為 0.299/0.587/0.114),視覺效果自然。
ColorTransform 配合)。BitmapData.getPixel/setPixel 逐像素處理快數量級。DisplayObject 會產生快取位圖(cacheAsBitmap=true),頻繁增刪濾鏡可能觸發重繪,建議複用 ColorMatrixFilter 實例。ColorTransform 暴力修改 RGB,AS3 推薦濾鏡方式非破壞性、可動畫化。