2011-02-24 97 views

回答

10

ColorMatrix營救!

引述的Android文檔,嘉洛斯:

用於轉化的位圖的 顏色+ alpha分量5x4的矩陣。矩陣被存儲在單個陣列中,並且其處理如下:[ a,b,c,d,e,f,g,h,i,j,k,l,m, n,o,當應用於 顏色[r,g,b,a]時,得到的顏色被計算爲(在鉗位後) 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;

設置從紅色通道(或綠色,或藍色,對灰度無關緊要)採用alpha值的顏色矩陣,然後在Paint.setColorFilter()中使用它。下面是一個或多或少的完整示例:

final BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inPreferredConfig = Bitmap.Config.ARGB_8888; 
options.inScaled = false; 

// Load source grayscale bitmap 
Bitmap grayscale = BitmapFactory.decodeResource(getResources(), R.drawable.my_grayscale_mask, options); 
// Place for alpha mask. It's specifically ARGB_8888 not ALPHA_8, 
// ALPHA_8 for some reason didn't work out for me. 
Bitmap alpha = Bitmap.createBitmap(grayscale.getWidth(), grayscale.getHeight(), 
     Bitmap.Config.ARGB_8888); 
float[] matrix = new float[] { 
     0, 0, 0, 0, 0, 
     0, 0, 0, 0, 0, 
     0, 0, 0, 0, 0, 
     1, 0, 0, 0, 0}; 
Paint grayToAlpha = new Paint(); 
grayToAlpha.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(matrix))); 
Canvas alphaCanvas = new Canvas(alpha); 
// Make sure nothing gets scaled during drawing 
alphaCanvas.setDensity(Bitmap.DENSITY_NONE); 
// Draw grayscale bitmap on to alpha canvas, using color filter that 
// takes alpha from red channel 
alphaCanvas.drawBitmap(grayscale, 0, 0, grayToAlpha); 
// Bitmap alpha now has usable alpha channel! 
+1

無論這個矩陣是否只將紅色通道從掩碼中取出?當然,如果源代碼真的是灰色的,這應該起作用。 mactix對於普通的RGB看起來如何?在我的底線「0.333,0.333,0.334,0,0」中,我想。是對的嗎? – 2015-02-23 08:12:06