package com.gh.gamecenter.core.utils

import android.graphics.Bitmap
import com.facebook.common.references.CloseableReference
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory
import com.facebook.imagepipeline.request.BasePostprocessor

class AlphaGradientProcess : BasePostprocessor() {

    override fun process(sourceBitmap: Bitmap, bitmapFactory: PlatformBitmapFactory): CloseableReference<Bitmap>? {
        val bitmapRef =
            bitmapFactory.createBitmap(getTransAlphaBitmap(sourceBitmap), 0, 0, sourceBitmap.width, sourceBitmap.height)
        return CloseableReference.cloneOrNull(bitmapRef)
    }

    /**
     * 设置图片的透明度从左到右渐变，使左边缘平滑过渡
     */
    private fun getTransAlphaBitmap(sourceImg: Bitmap): Bitmap {
        val width = sourceImg.width
        val height = sourceImg.height
        val bitArr = IntArray(width * height)
        sourceImg.getPixels(bitArr, 0, width, 0, 0, width, height)
        return try {
            val step = 100F / width
            for (h in 0 until height) {
                var number = 0F
                for (w in h * width until width * (h + 1)) {
                    number += step
                    val alpha = number * 255 / 100
                    bitArr[w] = alpha.toInt() shl 24 or (bitArr[w] and 0x00FFFFFF)
                }
            }
            Bitmap.createBitmap(bitArr, width, height, Bitmap.Config.ARGB_8888)
        } catch (e: Throwable) {
            sourceImg
        }
    }
}