通过 setGary方法来控制是否显示灰度图片
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by junjie on 2016/6/24.
*/
public class MyGaryImageView extends ImageView {
private boolean isGray = false;
public void setGray(boolean isGray){
this.isGray = isGray;
postInvalidate();
}
public MyGaryImageView(Context context) {
super(context);
}
public MyGaryImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGaryImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
if(getDrawable() == null){
return;
}
setImageDrawable(getDrawable());
super.onDraw(canvas);
}
public void setImageDrawable(@Nullable Drawable drawable) {
if(drawable == null){
return;
}
if(!isGray){
super.setImageDrawable(drawable);
}else {
super.setImageDrawable(getDrawable(drawable));
}
}
public Drawable getDrawable(Drawable drawable){
drawable.mutate();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
drawable.setColorFilter(cf);
return drawable;
}
}