如何在android中更改位图图像颜色? [英] How to change Bitmap image color in android?

查看:29
本文介绍了如何在android中更改位图图像颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 android 应用程序,我在其中将图像设置为 imageview.现在编程我想更改位图图像颜色.假设我的图像最初是红色的,现在我需要将其更改为橙色.我怎样才能做到这一点?请帮忙.

I am developing an android application in which I set an image to imageview. Now programmatic I want to change the bitmap image color. Suppose my image have red color initially and now I need to change it to orange color. How can I do that? Please help.

这是我的代码.我设法改变了不透明度,但我不知道如何改变颜色.

Here is my code. I managed to change the opacity but I do not know how to change the color.

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView iv = (ImageView) findViewById(R.id.img);
        Drawable d = getResources().getDrawable(R.drawable.pic1);
        Bitmap mNewBitmap = ((BitmapDrawable)d).getBitmap();
        Bitmap nNewBitmap = adjustOpacity(mNewBitmap);
        iv.setImageBitmap(nNewBitmap);
    }

    private Bitmap adjustOpacity( Bitmap bitmap ) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap dest = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        dest.setPixels(pixels, 0, width, 0, 0, width, height);
        return dest;
    } 

推荐答案

我找到了解决方案.

    Bitmap sourceBitmap = BitmapFactory.decodeFile(imgPath);
    float[] colorTransform = {
            0, 1f, 0, 0, 0, 
            0, 0, 0f, 0, 0,
            0, 0, 0, 0f, 0, 
            0, 0, 0, 1f, 0};

    ColorMatrix colorMatrix = new ColorMatrix();
    colorMatrix.setSaturation(0f); //Remove Colour 
    colorMatrix.set(colorTransform); //Apply the Red

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

    Display display = getWindowManager().getDefaultDisplay(); 

    Bitmap resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, (int)(display.getHeight() * 0.15), display.getWidth(), (int)(display.getHeight() * 0.75));            

    image.setImageBitmap(resultBitmap);

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

这篇关于如何在android中更改位图图像颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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