-1

我想灰度一个drawable。我正在尝试Justin 的建议,但它不适用于 Donut (1.6) 和 Eclair (2.1)。它适用于Android 2.2+。我正在尝试的代码如下:

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(filter);

有什么线索吗?

4

1 回答 1

1

这适用于较低的 Api,试试吧

 public Bitmap toGrayscale(Bitmap bmpOriginal)
    {        
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();    

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

如果您想使用画布或画家使用此代码,则无法为您的代码获取灰度图像,因为您使用了不可变的可绘制对象

Bitmap immutableBitmap = BitmapFactory.decodeResource(getResources(), 
    R.drawable.my_drawable);
Bitmap mutableBitmap = immutableBitmap.copy(Bitmap.Config.ARGB_8888, true);

//you have two bitmaps in memory, so clean up the mess a bit
immutableBitmap.recycle(); immutableBitmap=null;

Drawable d = new BitmapDrawable(mutableBitmap);

//mutate it
d.setColorFilter(new LightingColorFilter(color, lightenColor));

imageView.setImageDrawable(d);
于 2012-06-05T21:07:16.247 回答