2013-04-22 51 views
7

我想要更改圖像的某個部分的亮度。我知道如何使用ColorMatrix來改變圖像的亮度(或色調)。但它將應用於整個圖像。Android在imageView的一部分上應用colorMatrix colorFilter與蒙版

我有一個蒙版文件(黑白圖像)。我想在屏幕的白色部分應用亮度變化只有。如何在Android中執行此操作?

下面是一個蒙版圖像和我想要得到的結果。

enter image description here enter image description here

回答

11

對於給定的位圖和掩模:

bitmap.png

mask.png

第一創建臨時位圖:

bitmap = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.bitmap); 
mask = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.mask); 

float[] src = { 
    0, 0, 0, 0, 255, 
    0, 0, 0, 0, 255, 
    0, 0, 0, 0, 255, 
    1, 1, 1, -1, 0, 
}; 
ColorMatrix cm = new ColorMatrix(src); 
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(cm); 
maskPaint = new Paint(); 
maskPaint.setColorFilter(filter); 
maskPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); 

filteredBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); 
Canvas c = new Canvas(filteredBitmap); 
c.drawBitmap(bitmap, 0, 0, null); 
c.drawBitmap(mask, 0, 0, maskPaint); 

colorFilterPaint = new Paint(); 
colorFilterPaint.setColorFilter(new LightingColorFilter(0xffffff, 0x880000)); 

並繪製它(我換算起來,因爲我的模擬器縮放下來):

@Override 
public void draw(Canvas canvas) { 
    canvas.save(); 
    canvas.scale(3, 3); 
    canvas.drawBitmap(bitmap, 0, 0, null); 
    canvas.drawBitmap(filteredBitmap, 0, 0, colorFilterPaint); 
    canvas.restore(); 
} 

,其結果是:

enter image description here

1

你可以改變

float[] src = { 
0, 0, 0, 0, 255, 
0, 0, 0, 0, 255, 
0, 0, 0, 0, 255, 
1, 1, 1, -1, 0, 
}; 

float[] src = { 
0, 0, 0, 0, 255, 
0, 0, 0, 0, 255, 
0, 0, 0, 0, 255, 
1, 1, 1, 0, 0, 
}; 

給灰色部分更多的半透明。