Android:如何使位图的百分比变为黑白,其余部分保持颜色? [英] Android: How to make a percentage of a bitmap black and white, retaining color in the rest?

查看:135
本文介绍了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.

推荐答案

我在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.

从您的图像看来,您的意思是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:如何使位图的百分比变为黑白,其余部分保持颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆