主要原理:
PorterDuffColorFilter(int color, PorterDuff.Mode mode)
这个构造方法也接受两个值,一个是16进制表示的颜色值这个很好理解,而另一个是PorterDuff内部类Mode中的一个常量值,这个值表示混合模式。
PorterDuffColorFilter是ColorFilter的一个子类:
ColorFilter是对Drawable设置一个色彩过滤器。这是一个抽象类不能直接使用,他有三个子类:ColorMatrixColorFilter, LightingColorFilter, PorterDuffColorFilter 。
- ColorMatrixColorFilter 一个通过4*5的颜色矩阵来改变颜色的颜色过滤器;
- LightingColorFilter 一个可以模拟简单的灯光效果的颜色过滤器;
- PorterDuffColorFilter 一个可以使用单个颜色和指定Porter-Duff模式来对源像素进行染色颜色过滤器;
使用方法:
PorterDuffColorFilter(int color, PorterDuff.Mode mode) 构造器需要两个参数:
- color即我们需要渲染的颜色;
- mode即指定的指定Porter-Duff模式,如下图所示:
代码如下:
Bitmap transformBitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap resBitmap = Bitmap.createBitmap(transformBitmap.getWidth(), transformBitmap.getHeight(), transformBitmap.getConfig());
Canvas canvas = new Canvas(resBitmap);
Paint paint = new Paint();
paint.setColorFilter(new PorterDuffColorFilter(mColor, PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(transformBitmap, 0.0F, 0.0F, paint);
return resBitmap;
此外,android为我们提供了一个DrawableCompat类,通过它,我们可以更方便的对Drawable进行着色:
final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTintList(wrappedDrawable, colors);
//wrappedDrawable.mutate();
return wrappedDrawable;
在Glide中使用(自定义transform):
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
public class SetColorTransformGlide extends BitmapTransformation {
private int mColor;
private Context contxt;
public SetColorTransformGlide(Context context) {
super(context);
this.contxt=context;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return transform(toTransform);
}
public SetColorTransformGlide(Context context, int color) {
super(context);
this.mColor = color;
this.contxt=context;
}
public void setResourceColor(int resourceColor) {
this.mColor = contxt.getResources().getColor(resourceColor);
}
public void setColor(int color) {
this.mColor = color;
}
public int getWidth(Bitmap toTransform) {
return toTransform.getWidth();
}
public int getHeight(Bitmap toTransform) {
return toTransform.getHeight();
}
public Bitmap transform( Bitmap transformBitmap) {
Bitmap resBitmap = Bitmap.createBitmap(transformBitmap);
Canvas canvas = new Canvas(resBitmap);
Paint paint = new Paint();
paint.setColorFilter(new PorterDuffColorFilter(this.mColor, Mode.SRC_IN));
canvas.drawBitmap(transformBitmap, 0.0F, 0.0F, paint);
return resBitmap;
}
public String getId() {
return "SetColorTransform color" + this.mColor;
}
}