1.在xml中设置tint和tintMode实现对图片的着色,它通过修改图形的Alpha遮罩来修改图像的颜色,从而达到重新着色的目的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:src="@mipmap/icon_head" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:src="@mipmap/icon_head"
//此处为设置新颜色
android:tint="#FF4081" />
</LinearLayout>
2.利用DrawableCompat对图片进行动态颜色渲染
package com.per.tintdome;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView imageView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = (ImageView) findViewById(R.id.image1);
//利用ContextCompat工具类获取drawable图片资源
Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.icon_head);
//简单的使用tint改变drawable颜色
Drawable drawable1 = tintDrawable(drawable,ContextCompat.getColor(this, R.color.colorAccent));
imageView1.setImageDrawable(drawable1);
}
public static Drawable tintDrawable(Drawable drawable, int colors) {
final Drawable wrappedDrawable = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTint(wrappedDrawable, colors);
return wrappedDrawable;
}
}