2011-09-23 81 views
0

我想更改imageview中存在的圖像的顏色。我從Bitmap對象的imageview中獲取圖像,並在其上應用了colormatrix。 問題是,一旦我改變圖像的顏色,它不會改變bt覆蓋以前的顏色,我想要的是,當我改變顏色時,圖像的以前的顏色應該被刪除,並且任何特定的顏色,我選擇應用。更改圖像的顏色android

我用下面的代碼來做到這一點...

void setImageColor(RGBColor rgbcolor,ImageView view)//,Bitmap sourceBitmap) 
    { 
     view.setDrawingCacheEnabled(true); 
     Bitmap sourceBitmap = view.getDrawingCache(); 
     if(sourceBitmap!=null) 
     { 
     float R = (float)rgbcolor.getR(); 
     float G = (float)rgbcolor.getG(); 
     float B = (float)rgbcolor.getB(); 

     Log.v("R:G:B",R+":"+G+":"+B);  

     float[] colorTransform = 
     { R/255f, 0, 0, 0, 0, // R color 
      0, G/255f, 0, 0, 0, // G color 
      0, 0, B/255f, 0, 0, // B color 
      0, 0, 0, 1f, 0f 
     };     

     ColorMatrix colorMatrix = new ColorMatrix(); 
     colorMatrix.setSaturation(0f); //Remove Colour 

     colorMatrix.set(colorTransform); 
     ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix); 
     Paint paint = new Paint(); 
     paint.setColorFilter(colorFilter); 

     Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true); 
     view.setImageBitmap(mutableBitmap); 
     Canvas canvas = new Canvas(mutableBitmap); 
     canvas.drawBitmap(mutableBitmap, 0, 0, paint);  
     } 
     else 
      return; 
    } 
+0

你有答案的答案嗎? – ALiGOTec

回答

1

聲明靜態sourceBitmap而做到這一點只有一次:Bitmap sourceBitmap = view.getDrawingCache();讓我們在你的活動onResume()說(或當您更改的ImageView圖像)。

而且你的功能應該是:

void setImageColor(RGBColor rgbcolor, ImageView view, Bitmap sourceBitmap) { 
    if (sourceBitmap == null) return; 

    float r = (float) rgbcolor.getR(), 
      g = (float) rgbcolor.getG(), 
      b = (float) rgbcolor.getB(); 

    Log.v("R:G:B", r + ":" + g + ":" + b);  

    float[] colorTransform = 
    {  
     r/255, 0 , 0 , 0, 0, // R color 
     0 , g/255, 0 , 0, 0, // G color 
     0 , 0 , b/255, 0, 0, // B color 
     0 , 0 , 0 , 1, 0 
    }; 

    ColorMatrix colorMatrix = new ColorMatrix(); 
    colorMatrix.setSaturation(0f); // Remove colour 
    colorMatrix.set(colorTransform); 

    ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix); 

    Paint paint = new Paint(); 
    paint.setColorFilter(colorFilter); 

    Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true); 
    view.setImageBitmap(mutableBitmap); 

    Canvas canvas = new Canvas(mutableBitmap); 
    canvas.drawBitmap(mutableBitmap, 0, 0, paint);  
} 

這樣,您將保持不變圖像與原始應用過濾器。