chagnge color of shape drawable programatically

纵然是瞬间 提交于 2020-01-05 08:20:34

问题


i need to chage color of shape drawable programatically...

i am using this

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/app_theme_blue" />
    <corners android:radius="8dp" />
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
</shape>

Here i required to change color of android:color="@color/app_theme_blue" . please help me.


回答1:


Yes, you can. And it's really super easy.

First of all, keep in mind that it's easier to work with white images, in order to have a neutral source to apply the colour to (so, imagine to have a white contour on a transparent background).

Drawable drw = mContext.getResources().getDrawable(R.id.baseDrawable);

What this line does is simply getting the Drawable from the resources (baseDrawable - name it whatever you like).

Next, we're going to use an overload of the setColorFilter() method which accetpts two parameters: the color we want and the blending mode.

Note that the Drawable is unmutable by default, so we have to make it mutable, in order to apply any transformations to it.

drw.mutate().setColorFilter(finalColor, PorterDuff.Mode.MULTIPLY);

Now you can concentrate on your software, without the need to make many variations of the same resource.

By the way, there's no API Level requirement, it works since API Level 1.

P.S.:

These are the required imports:

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;


来源:https://stackoverflow.com/questions/24166092/chagnge-color-of-shape-drawable-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!