本文介绍了Android:如何使位图的百分比变为黑白,其余部分保持颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在ImageView
中显示了一个位图,我希望能够将图像的一定百分比变成黑白,并让其他部分保留其颜色.例如,如果60%是目标百分比,则图像将如下所示:.谢谢.
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: . Thanks.
推荐答案
从您的图像看来,您的意思是monochrome
(即greyscale
),而不是黑白的.
It seems (from your image) you mean monochrome
(i.e. greyscale
), not black and white.
应该执行以下操作(经过 o.k.测试):
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 ;
}
这篇关于Android:如何使位图的百分比变为黑白,其余部分保持颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!