How to change color of drawable shapes in android

前端 未结 6 896
时光取名叫无心
时光取名叫无心 2020-12-09 15:09

I am developing small android application in which I set drawable resource as background for linear layout. Now what I want to do change background color of linear layout dy

6条回答
  •  时光取名叫无心
    2020-12-09 15:56

    You could try something like this :

    Drawable sampleDrawable = context.getResources().getDrawable(R.drawable.balloons); 
    sampleDrawable.setColorFilter(new PorterDuffColorFilter(0xffff00,PorterDuff.Mode.MULTIPLY));
    

    and for more you could refer to :

    How to change colors of a Drawable in Android?

    Change drawable color programmatically

    Android: Change Shape Color in runtime

    http://pastebin.com/Hd2aU4XC

    You could also try this :

    private static final int[] FROM_COLOR = new int[]{49, 179, 110};
    private static final int THRESHOLD = 3;
    
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_colors);
    
        ImageView iv = (ImageView) findViewById(R.id.img);
        Drawable d = getResources().getDrawable(RES);
        iv.setImageDrawable(adjust(d));
    }
    
    private Drawable adjust(Drawable d)
    {
        int to = Color.RED;
    
        //Need to copy to ensure that the bitmap is mutable.
        Bitmap src = ((BitmapDrawable) d).getBitmap();
        Bitmap bitmap = src.copy(Bitmap.Config.ARGB_8888, true);
        for(int x = 0;x < bitmap.getWidth();x++)
            for(int y = 0;y < bitmap.getHeight();y++)
                if(match(bitmap.getPixel(x, y))) 
                    bitmap.setPixel(x, y, to);
    
        return new BitmapDrawable(bitmap);
    }
    
    private boolean match(int pixel)
    {
        //There may be a better way to match, but I wanted to do a comparison ignoring
        //transparency, so I couldn't just do a direct integer compare.
        return Math.abs(Color.red(pixel) - FROM_COLOR[0]) < THRESHOLD && Math.abs(Color.green(pixel) - FROM_COLOR[1]) < THRESHOLD && Math.abs(Color.blue(pixel) - FROM_COLOR[2]) < THRESHOLD;
    }
    

    as given in How to change colors of a Drawable in Android?

提交回复
热议问题