如何在Android中改变可绘图的颜色?

时间:2022-11-21 12:15:41

I'm working on an android application, and I have a drawable that I'm loading up from a source image. On this image, I'd like to convert all of the white pixels to a different color, say blue, and then cache the resultant Drawable object so I can use it later.

我正在开发一个android应用程序,我有一个从源映像加载的可绘图程序。在这张图片上,我想将所有的白色像素转换成不同的颜色,比如蓝色,然后缓存生成的可绘制对象,以便稍后使用。

So for example say I have a 20x20 PNG file that has a white circle in the middle, and that everything outside the circle is transparent. What's the best way to turn that white circle blue and cache the results? Does the answer change if I want to use that source image to create several new Drawables (say blue, red, green, orange, etc)?

例如,我有一个20x20的PNG文件,它中间有一个白色的圆圈,圆圈外面的一切都是透明的。将白色圆圈变为蓝色并缓存结果的最佳方法是什么?如果我想使用源映像创建几个新的可绘制对象(比如蓝色、红色、绿色、橙色等),那么答案是否会改变?

I'm guessing that I'll want to use a ColorMatrix in some way, but I'm not sure how.

我猜我可能想以某种方式使用一个ColorMatrix,但我不确定如何使用。

17 个解决方案

#1


191  

I think you can actually just use Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY ). This would set white pixels to red but I don't think it would affect the transparent pixels.

我认为你可以用Drawable。setColorFilter(0 xffff0000模式。用)。这将把白色像素设为红色,但我认为它不会影响透明像素。

See Drawable#setColorFilter

看到可拉的# setColorFilter

#2


127  

Give this code a try:

试试下面的代码:

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);

#3


74  

I know this question was ask way before Lollipop but I would like to add a nice way to do this on Android 5.+. You make an xml drawable that references the original one and set tint on it like such:

我知道这个问题在Lollipop之前就已经问过了,但是我想在Android 5上添加一个很好的方法。您可以使一个xml drawable引用原始的一个,并在它上面设置颜色:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

Check out my blog post on this for more information.

查看我的博客上的更多信息。

#4


59  

If you have a drawable that's a solid color and you want to change it to a differnet solid color, you can use a ColorMatrixColorFilter. Transparency is preserved.

如果你有一个固定的颜色,你想把它换成不同的纯色,你可以使用ColorMatrixColorFilter。透明度是保存。

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

#5


52  

The new support v4 bring tint back to api 4.

新的支持v4将色调带回api 4。

you can do it like this

你可以这样做

public static Drawable setTint(Drawable d, int color) {
    Drawable wrappedDrawable = DrawableCompat.wrap(d);
    DrawableCompat.setTint(wrappedDrawable, color);
    return wrappedDrawable;
}

#6


39  

You should do this for all APIs:

对于所有的api,您都应该这样做:

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

#7


34  

I also use ImageView for icons (in ListView or settings screen). But I think there is much simpler way to do that.

我还对图标使用ImageView(在ListView或settings屏幕上)。但我认为有更简单的方法。

Use tint to change the color overlay on your selected icon.

使用tint改变选定图标的颜色覆盖。

In xml,

在xml中,

android:tint="@color/accent"
android:src="@drawable/ic_event"

android:色= " @color /口音”android:src = " @drawable / ic_event "

works fine since it comes from AppCompat

很好,因为它来自AppCompat。

#8


30  

I was able to do this with the following code, which is taken from an activity (the layout is a very simple one, just containing an ImageView, and is not posted here).

我可以使用以下代码来实现这一点,这些代码来自一个活动(布局非常简单,只包含一个ImageView,不在这里发布)。

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;
}

#9


15  

In your Activity you can tint your PNG image resources with a single colour:

在您的活动中,您可以使用单一颜色来着色您的PNG图像资源:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myColorTint();
    setContentView(R.layout.activity_main);
}

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); // R.color.blue;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);
        icon.setColorFilter(tint,mode);
    }
}

Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

现在当你使用r。drawable。*应该用你想要的颜色。如果您需要其他颜色,那么您应该能够.mutate()绘制的图形。

#10


7  

You can solve it using Android support compat libraries. :)

您可以使用Android支持的compat库来解决这个问题。:)

Drawable drawableWrap = DrawableCompat.wrap(drawable);
drawableWrap.mutate(); // to not share its state with any other drawable
DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color));

#11


3  

Check out this sample code "ColorMatrixSample.java"

请查看示例代码“ColorMatrixSample.java”

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.graphics;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public class ColorMatrixSample extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private ColorMatrix mCM = new ColorMatrix();
        private Bitmap mBitmap;
        private float mSaturation;
        private float mAngle;

        public SampleView(Context context) {
            super(context);

            mBitmap = BitmapFactory.decodeResource(context.getResources(),
                                                   R.drawable.balloons);
        }

        private static void setTranslate(ColorMatrix cm, float dr, float dg,
                                         float db, float da) {
            cm.set(new float[] {
                   2, 0, 0, 0, dr,
                   0, 2, 0, 0, dg,
                   0, 0, 2, 0, db,
                   0, 0, 0, 1, da });
        }

        private static void setContrast(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, translate,
                   0, scale, 0, 0, translate,
                   0, 0, scale, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastTranslateOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   1, 0, 0, 0, translate,
                   0, 1, 0, 0, translate,
                   0, 0, 1, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastScaleOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, 0,
                   0, scale, 0, 0, 0,
                   0, 0, scale, 0, 0,
                   0, 0, 0, 1, 0 });
        }

        @Override protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;
            float x = 20;
            float y = 20;

            canvas.drawColor(Color.WHITE);

            paint.setColorFilter(null);
            canvas.drawBitmap(mBitmap, x, y, paint);

            ColorMatrix cm = new ColorMatrix();

            mAngle += 2;
            if (mAngle > 180) {
                mAngle = 0;
            }

            //convert our animated angle [-180...180] to a contrast value of [-1..1]
            float contrast = mAngle / 180.f;

            setContrast(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x + mBitmap.getWidth() + 10, y, paint);

            setContrastScaleOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + mBitmap.getHeight() + 10, paint);

            setContrastTranslateOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + 2*(mBitmap.getHeight() + 10),
                              paint);

            invalidate();
        }
    }
}

The relevant API is available here:

有关的空气污染指数载于此:

#12


3  

There are so many solution but nobody suggested if the color resource xml file already have color then we can pick directly from there also as below:

有这么多的解决方案,但是没有人建议如果颜色资源xml文件已经有颜色,那么我们可以直接从那里选择如下:

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

#13


2  

This works with everything with background:

这适用于所有有背景的东西:

Textview, Button...

Textview,按钮……

TextView text = (TextView) View.findViewById(R.id.MyText);
text.setBackgroundResource(Icon);    
text.getBackground().setColorFilter(getResources().getColor(Color), PorterDuff.Mode.SRC_ATOP);

#14


2  

view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY); 

Thanks to @sabadow

由于@sabadow

#15


2  

This code snippet worked for me:

这个代码片段对我很有用:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

#16


1  

Short example to change drawable color according to isWorking field.

根据isWorking field改变可拉伸颜色的简短示例。

My shape xml:

我的形状xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_bright" />
    <corners android:radius="30dp" />
    <size
        android:height="15dp"
        android:width="15dp" />
</shape>

My method to change:

改变我的方法:

private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
    Drawable d = getResources().getDrawable(R.drawable.shape);
    ColorFilter filter = new LightingColorFilter(
            isworking ? Color.GREEN : Color.RED,
            isworking ? Color.GREEN : Color.RED);
    d.setColorFilter(filter);
    return d;
}

Example of usage:

使用的例子:

text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);

#17


0  

It's very very simple when you use a library to do that for you. Try this library

当你使用一个库为你做这个的时候,它是非常简单的。试试这个图书馆

You can call like this:

你可以这样打电话:

Icon.on(holderView).color(R.color.your_color).icon(R.mipmap.your_icon).put();

#1


191  

I think you can actually just use Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY ). This would set white pixels to red but I don't think it would affect the transparent pixels.

我认为你可以用Drawable。setColorFilter(0 xffff0000模式。用)。这将把白色像素设为红色,但我认为它不会影响透明像素。

See Drawable#setColorFilter

看到可拉的# setColorFilter

#2


127  

Give this code a try:

试试下面的代码:

ImageView lineColorCode = (ImageView)convertView.findViewById(R.id.line_color_code);
int color = Color.parseColor("#AE6118"); //The color u want             
lineColorCode.setColorFilter(color);

#3


74  

I know this question was ask way before Lollipop but I would like to add a nice way to do this on Android 5.+. You make an xml drawable that references the original one and set tint on it like such:

我知道这个问题在Lollipop之前就已经问过了,但是我想在Android 5上添加一个很好的方法。您可以使一个xml drawable引用原始的一个,并在它上面设置颜色:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

Check out my blog post on this for more information.

查看我的博客上的更多信息。

#4


59  

If you have a drawable that's a solid color and you want to change it to a differnet solid color, you can use a ColorMatrixColorFilter. Transparency is preserved.

如果你有一个固定的颜色,你想把它换成不同的纯色,你可以使用ColorMatrixColorFilter。透明度是保存。

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

#5


52  

The new support v4 bring tint back to api 4.

新的支持v4将色调带回api 4。

you can do it like this

你可以这样做

public static Drawable setTint(Drawable d, int color) {
    Drawable wrappedDrawable = DrawableCompat.wrap(d);
    DrawableCompat.setTint(wrappedDrawable, color);
    return wrappedDrawable;
}

#6


39  

You should do this for all APIs:

对于所有的api,您都应该这样做:

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

#7


34  

I also use ImageView for icons (in ListView or settings screen). But I think there is much simpler way to do that.

我还对图标使用ImageView(在ListView或settings屏幕上)。但我认为有更简单的方法。

Use tint to change the color overlay on your selected icon.

使用tint改变选定图标的颜色覆盖。

In xml,

在xml中,

android:tint="@color/accent"
android:src="@drawable/ic_event"

android:色= " @color /口音”android:src = " @drawable / ic_event "

works fine since it comes from AppCompat

很好,因为它来自AppCompat。

#8


30  

I was able to do this with the following code, which is taken from an activity (the layout is a very simple one, just containing an ImageView, and is not posted here).

我可以使用以下代码来实现这一点,这些代码来自一个活动(布局非常简单,只包含一个ImageView,不在这里发布)。

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;
}

#9


15  

In your Activity you can tint your PNG image resources with a single colour:

在您的活动中,您可以使用单一颜色来着色您的PNG图像资源:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myColorTint();
    setContentView(R.layout.activity_main);
}

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); // R.color.blue;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);
        icon.setColorFilter(tint,mode);
    }
}

Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

现在当你使用r。drawable。*应该用你想要的颜色。如果您需要其他颜色,那么您应该能够.mutate()绘制的图形。

#10


7  

You can solve it using Android support compat libraries. :)

您可以使用Android支持的compat库来解决这个问题。:)

Drawable drawableWrap = DrawableCompat.wrap(drawable);
drawableWrap.mutate(); // to not share its state with any other drawable
DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color));

#11


3  

Check out this sample code "ColorMatrixSample.java"

请查看示例代码“ColorMatrixSample.java”

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.graphics;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public class ColorMatrixSample extends GraphicsActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SampleView(this));
    }

    private static class SampleView extends View {
        private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private ColorMatrix mCM = new ColorMatrix();
        private Bitmap mBitmap;
        private float mSaturation;
        private float mAngle;

        public SampleView(Context context) {
            super(context);

            mBitmap = BitmapFactory.decodeResource(context.getResources(),
                                                   R.drawable.balloons);
        }

        private static void setTranslate(ColorMatrix cm, float dr, float dg,
                                         float db, float da) {
            cm.set(new float[] {
                   2, 0, 0, 0, dr,
                   0, 2, 0, 0, dg,
                   0, 0, 2, 0, db,
                   0, 0, 0, 1, da });
        }

        private static void setContrast(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, translate,
                   0, scale, 0, 0, translate,
                   0, 0, scale, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastTranslateOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   1, 0, 0, 0, translate,
                   0, 1, 0, 0, translate,
                   0, 0, 1, 0, translate,
                   0, 0, 0, 1, 0 });
        }

        private static void setContrastScaleOnly(ColorMatrix cm, float contrast) {
            float scale = contrast + 1.f;
               float translate = (-.5f * scale + .5f) * 255.f;
            cm.set(new float[] {
                   scale, 0, 0, 0, 0,
                   0, scale, 0, 0, 0,
                   0, 0, scale, 0, 0,
                   0, 0, 0, 1, 0 });
        }

        @Override protected void onDraw(Canvas canvas) {
            Paint paint = mPaint;
            float x = 20;
            float y = 20;

            canvas.drawColor(Color.WHITE);

            paint.setColorFilter(null);
            canvas.drawBitmap(mBitmap, x, y, paint);

            ColorMatrix cm = new ColorMatrix();

            mAngle += 2;
            if (mAngle > 180) {
                mAngle = 0;
            }

            //convert our animated angle [-180...180] to a contrast value of [-1..1]
            float contrast = mAngle / 180.f;

            setContrast(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x + mBitmap.getWidth() + 10, y, paint);

            setContrastScaleOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + mBitmap.getHeight() + 10, paint);

            setContrastTranslateOnly(cm, contrast);
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            canvas.drawBitmap(mBitmap, x, y + 2*(mBitmap.getHeight() + 10),
                              paint);

            invalidate();
        }
    }
}

The relevant API is available here:

有关的空气污染指数载于此:

#12


3  

There are so many solution but nobody suggested if the color resource xml file already have color then we can pick directly from there also as below:

有这么多的解决方案,但是没有人建议如果颜色资源xml文件已经有颜色,那么我们可以直接从那里选择如下:

ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setColorFilter(getString(R.color.your_color));

#13


2  

This works with everything with background:

这适用于所有有背景的东西:

Textview, Button...

Textview,按钮……

TextView text = (TextView) View.findViewById(R.id.MyText);
text.setBackgroundResource(Icon);    
text.getBackground().setColorFilter(getResources().getColor(Color), PorterDuff.Mode.SRC_ATOP);

#14


2  

view.getDrawable().mutate().setColorFilter(0xff777777, PorterDuff.Mode.MULTIPLY); 

Thanks to @sabadow

由于@sabadow

#15


2  

This code snippet worked for me:

这个代码片段对我很有用:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)

#16


1  

Short example to change drawable color according to isWorking field.

根据isWorking field改变可拉伸颜色的简短示例。

My shape xml:

我的形状xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_bright" />
    <corners android:radius="30dp" />
    <size
        android:height="15dp"
        android:width="15dp" />
</shape>

My method to change:

改变我的方法:

private Drawable getColoredDrawable(int drawableResId, boolean isworking) {
    Drawable d = getResources().getDrawable(R.drawable.shape);
    ColorFilter filter = new LightingColorFilter(
            isworking ? Color.GREEN : Color.RED,
            isworking ? Color.GREEN : Color.RED);
    d.setColorFilter(filter);
    return d;
}

Example of usage:

使用的例子:

text1.setCompoundDrawablesWithIntrinsicBounds(getColoredDrawable(R.drawable.shape, isworking()), null, null, null);

#17


0  

It's very very simple when you use a library to do that for you. Try this library

当你使用一个库为你做这个的时候,它是非常简单的。试试这个图书馆

You can call like this:

你可以这样打电话:

Icon.on(holderView).color(R.color.your_color).icon(R.mipmap.your_icon).put();