美文网首页
Android开发图片滤镜效果 Kotlin语言

Android开发图片滤镜效果 Kotlin语言

作者: 没有小叮当的大雄 | 来源:发表于2022-06-24 14:12 被阅读0次

Android手机上给ImageView展示的图片增加滤镜,
先看一下原图效果:

1301656049854_.pic.jpg

这个是增加了滤镜的效果


1311656049854_.pic.jpg

基本原理:
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
希望各位同行多多交流,帮助中小厂的同学重复造轮子,每天按时下班~~

相关文章

网友评论

      本文标题:Android开发图片滤镜效果 Kotlin语言

      本文链接:https://www.haomeiwen.com/subject/mvpvvrtx.html