2012-08-15 130 views
3

我有一個帶有位圖的ImageView。該位圖具有Alpha通道和透明像素。 當我嘗試使用ColorFiter與Mode.OVERLAY(因爲蜂窩) - 提供的顏色覆蓋整個imageview(整個矩形),但我只想覆蓋非透明像素。我如何剪切imageview的畫布以執行我想要的過濾器?ImageView ColorFilter在非透明像素上。 Clip

修訂

我有灰色的形象PNG:

enter image description here

當我嘗試使用MODE_ATOP我得到:

enter image description here

當我使用OVERLAY我得到:

enter image description here

什麼,我想:

enter image description here

回答

3

有可能做到這一點(也許通過創建一個ColorMatrixColorFilter接近它)更有效的方式,但由於Mode.OVERLAY似乎是hard to simplify otherwise,這裏有一些示例代碼應該實現你想要的:

public class MyActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     final ImageView imageView = new ImageView(this); 
     setContentView(imageView); 

     final Paint paint = new Paint(); 
     Canvas c; 

     final Bitmap src = BitmapFactory.decodeResource(getResources(), 
       android.R.drawable.sym_def_app_icon); 
     final int overlayColor = Color.RED; 

     final Bitmap bm1 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888); 
     c = new Canvas(bm1); 
     paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.OVERLAY)); 
     c.drawBitmap(src, 0, 0, paint); 

     final Bitmap bm2 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888); 
     c = new Canvas(bm2); 
     paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.SRC_ATOP)); 
     c.drawBitmap(src, 0, 0, paint); 

     paint.setColorFilter(null); 
     paint.setXfermode(new AvoidXfermode(overlayColor, 0, Mode.TARGET)); 
     c.drawBitmap(bm1, 0, 0, paint); 

     imageView.setImageBitmap(bm2); 
    } 

} 

總之,我們畫t他使用OVERLAY模式來源位圖和顏色,然後使用輔助位圖(使用SRC_ATOP模式進行合成),我們使用AvoidXfermode將其組合起來,以不繪製透明像素。

原圖:

original image

結果:

result

+0

謝謝你,我會嘗試,現在,如果你現在如何實現這一目標使用彩色矩陣可以給一個關於如何做到這一點的教程/示例/文檔的鏈接? – dilix 2012-08-23 08:24:43

+0

我試過了你的樣品,但是結果並不是這樣,我已經用圖片粘貼了更新的問題 – dilix 2012-08-23 08:55:32

+0

嗯..我似乎得到了你想要的結果,讓我把截圖上傳到我的答案。 – Joe 2012-08-23 13:06:06