Android開發(fā)圖片濾鏡效果 Kotlin語言

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;
    }

入?yún)olorFilter可以是null,代表不加濾鏡效果.

2.ColorFilter的構造方法會接收一個4*5的數(shù)組:

    public ColorMatrixColorFilter(@NonNull float[] array) {
        if (array.length < 20) {
            throw new ArrayIndexOutOfBoundsException();
        }
        mMatrix.set(array);
    }

3.ColorFilter的mMatrix會根據(jù)4*5的數(shù)組來設置濾鏡,具體對應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類當做參數(shù)傳入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語言開發(fā),最后附上Demo地址:
https://github.com/cgztzero/imagefilter/tree/master
希望各位同行多多交流,幫助中小廠的同學重復造輪子,每天按時下班~~

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容