I've got a bitmap displayed in an ImageView, and I want to be able to make a certain percentage of the image black and white, and have the other part retain it's color. For example, if 60% is the target percentage, the image would look like this:

9lQu9.png. Thanks.

解决方案I've got a bitmap displayed in an ImageView, and I want to be able to

make a certain percentage of the image black and white, and have the

other part retain it's color. For example, if 60% is the target

percentage.

It seems (from your image) you mean monochrome (i.e. greyscale), not black and white.

Something like this should do it (tested o.k.):

void doIt(ImageView image)

{

//get bitmap from your ImageView (image)

Bitmap originalBitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

int height = originalBitmap.getHeight();

int fortyPercentHeight = (int) Math.floor(height * 40.0 / 100.0);

//create a bitmap of the top 40% of image height that we will make black and white

Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth() , fortyPercentHeight );

//make it monochrome

Bitmap blackAndWhiteBitmap = monoChrome(croppedBitmap);

//copy the monochrome bmp (blackAndWhiteBitmap) to the original bmp (originalBitmap)

originalBitmap = overlay(originalBitmap, blackAndWhiteBitmap);

//set imageview to new bitmap

image.setImageBitmap(originalBitmap );

}

Bitmap monoChrome(Bitmap bitmap)

{

Bitmap bmpMonochrome = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bmpMonochrome);

ColorMatrix ma = new ColorMatrix();

ma.setSaturation(0);

Paint paint = new Paint();

paint.setColorFilter(new ColorMatrixColorFilter(ma));

canvas.drawBitmap(bitmap, 0, 0, paint);

return bmpMonochrome;

}

Bitmap overlay(Bitmap bmp1, Bitmap bmp2)

{

Bitmap bmp3 = bmp1.copy(Bitmap.Config.ARGB_8888,true);//mutable copy

Canvas canvas = new Canvas(bmp3 );

canvas.drawBitmap(bmp2, new Matrix(), null);

return bmp3 ;

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐