Android手机上给ImageView展示的图片增加滤镜,
先看一下原图效果:
这个是增加了滤镜的效果
基本原理:
1.View的绘制都会用到Paint类,Paint类会公开了一个方法,可以直接设置ColorFilter:
public ColorFilter setColorFilter(ColorFilter filter) {
// If mColorFilter changes, cached value of native shader aren't valid, since
// old shader's pointer may be reused by another shader allocation later
if (mColorFilter != filter) {
mNativeColorFilter = -1;
}
// Defer setting the filter natively until getNativeInstance() is called
mColorFilter = filter;
return filter;
}
入参ColorFilter可以是null,代表不加滤镜效果.
2.ColorFilter的构造方法会接收一个4*5的数组:
public ColorMatrixColorFilter(@NonNull float[] array) {
if (array.length < 20) {
throw new ArrayIndexOutOfBoundsException();
}
mMatrix.set(array);
}
3.ColorFilter的mMatrix会根据4*5的数组来设置滤镜,具体对应RGBA,官方注释中写的也很清楚:
4x5 matrix for transforming the color and alpha components of a Bitmap. The matrix can be passed as single array, and is treated as follows:
[ a, b, c, d, e,
f, g, h, i, j,
k, l, m, n, o,
p, q, r, s, t ]
When applied to a color [R, G, B, A], the resulting color is computed as:
R’ = a*R + b*G + c*B + d*A + e;
G’ = f*R + g*G + h*B + i*A + j;
B’ = k*R + l*G + m*B + n*A + o;
A’ = p*R + q*G + r*B + s*A + t;
4.最后直接把Paint类当做参数传入View中即可看到效果,不只是ImageView有效,对TextView中的文字同样有效:
val paint = Paint()
if (position == 0) {
paint.colorFilter = null
} else {
paint.colorFilter = ColorMatrixColorFilter(FilterData.filters[position].filterArray!!)
}
binding.textView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
binding.image.setLayerType(View.LAYER_TYPE_SOFTWARE, paint)
Kotlin语言开发,最后附上Demo地址:
https://github.com/cgztzero/imagefilter/tree/master
希望各位同行多多交流,帮助中小厂的同学重复造轮子,每天按时下班~~