這次,我將向大家分享,如何利用另一種 Matrix - ColorMatrix,來做出負片與灰階效果。
最上面那張圖的上半部,是原來的影像,一個美麗的地球。下半部的左邊,就是這地球影像的負片效果。右邊,則是灰階效果的呈現。
負片效果
負片效果的演算法,很簡單。就像底下這樣。
- R' = 255 - R;
- G' = 255 - G;
- B' = 255 - B;
當然不是!這樣的做法,太沒效率,速度一定很慢。在 Android 中,針對這樣的需求,你可以透過 ColorMatrixColorFilter 來完成。在建構一個 ColorMatrixColorFilter 時,你得傳給他一個 ColorMatrix。因此,重點就在這個 ColorMatrix。
ColorMatrix 文件一開頭的註釋,就已經將他的功能講得很清楚。
- //5x4 matrix for transforming the color+alpha components of a Bitmap.
- //The matrix is stored in a single array, and its treated as follows:
- //[ a, b, c, d, e,
- // f, g, h, i, j,
- // k, l, m, n, o,
- // p, q, r, s, t ]
- //
- //When applied to a color [r, g, b, a], the resulting color is computed as
- //(after clamping)
- // R' = a*R + b*G + c*B + d*A + e;
- // G' = f*R + g*G + h*B + i*A + j;
- // B' = k*R + l*G + m*B + n*A + o;
- // A' = p*R + q*G + r*B + s*A + t;
- Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
- ColorMatrix cm = new ColorMatrix(new float[] {
- -1f, 0f, 0f, 0f, 255f,
- 0f, -1f, 0f, 0f, 255f,
- 0f, 0f, -1f, 0f, 255f,
- 0f, 0f, 0f, 1f, 0f});
- paint.setColorFilter(new ColorMatrixColorFilter(cm));
- canvas.drawBitmap(m_bmp, 0, 0, paint);
灰階效果
負片會了,灰階應該也很簡單了吧!我告訴你,要完成灰階效果,更簡單。ColorMatrix 都幫你將算法寫好了。你只要呼叫 ColorMatrix.setSaturation(0) 即可。
等等,學東西,可不能這樣就含混帶過。別忘了,Android 的原始碼都給你了,我們得利用他追根究柢,一探究竟才行。
打開 ColorMatrix.java 的原始碼,翻到 setSaturation()。這個函式的實現如下:
- public void setSaturation(float sat) {
- reset();
- float[] m = mArray;
- final float invSat = 1 - sat;
- final float R = 0.213f * invSat;
- final float G = 0.715f * invSat;
- final float B = 0.072f * invSat;
- m[0] = R + sat; m[1] = G; m[2] = B;
- m[5] = R; m[6] = G + sat; m[7] = B;
- m[10] = R; m[11] = G; m[12] = B + sat;
- }
很多好東西,就在你身旁,千萬別捨近求遠了。
資料來源:
http://ysl-paradise.blogspot.com/2010/01/iii.html
沒有留言:
張貼留言