我有一个在drawable中的png图标。它是黑色的,背景透明。如何在不添加其他drawable的情况下更改图标颜色?
我有一个在drawable中的png图标。它是黑色的,背景透明。如何在不添加其他drawable的情况下更改图标颜色?
Drawable mIcon= ContextCompat.getDrawable(getActivity(), R.drawable.your_icon);
mIcon.setColorFilter(ContextCompat.getColor(getActivity(), R.color.new_color), PorterDuff.Mode.MULTIPLY);
mImageView.setImageDrawable(mIcon);
public Drawable getTintedDrawable(Resources res,
@DrawableRes int drawableResId, @ColorRes int colorResId) {
Drawable drawable = res.getDrawable(drawableResId);
int color = res.getColor(colorResId);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
return drawable;
}
尝试使用这个静态方法:
public static Drawable changeDrawableColor(Drawable drawable, int color) {
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, color);
return drawable;
}
color参数可以是来自您资源中的颜色。
PorterDuff.Mode.SRC_IN
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Drawable mIcon= ContextCompat.getDrawable(this, R.drawable.icon_send);
mIcon.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.SRC_IN);
ibSendMessage.setBackground(mIcon);
}
android:backgroundTint="@color/colorAccent"
backgroundTint
对我没用,目前我正在使用 Android Studio 4.0。 - syed dastagirDrawable mDrawable = context.getResources().getDrawable(R.drawable.balloons);
mDrawable.setColorFilter(new
PorterDuffColorFilter(0xffff00,PorterDuff.Mode.LIGHTEN));
尝试使用上述代码,您可以使用PorterDuffColorFilter(0xffff00,PorterDuff.Mode.LIGHTEN)进行操作 您也可以使用黑色等其他颜色。
public void ChangePngIconColor(String Target_Color, ImageView Target_ImageView){
/*
* Sample:
* Target_Color = "#efec0c"; OR Target_Color = "efec0c";
*
*/
Target_Color = (Target_Color.startsWith("#")) ? Target_Color : "#"+Target_Color;
Target_ImageView.setColorFilter(Color.parseColor(Target_Color), PorterDuff.Mode.SRC_IN);
}
public void ChangePngIconColor(int Target_Color_ID, ImageView Target_ImageView){
/*
* Sample: Target_Color = R.color.white;
*
*/
Target_ImageView.setColorFilter(ContextCompat.getColor(context,Target_Color_ID), PorterDuff.Mode.SRC_IN);
}
Resources
上的Kotlin扩展函数,没有过时的问题。fun Resources.tintedDrawable(
@DrawableRes drawableResId: Int, @ColorRes colorResId: Int
): Drawable? {
val drawable = ResourcesCompat.getDrawable(this, drawableResId, null)
val color = ResourcesCompat.getColor(this, colorResId, null)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
drawable?.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_IN)
else
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_IN)
return drawable
}
resources.tintedDrawable(R.drawable.my_drawable, R.color.my_tint)