package com.ym.library.utils

import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.MotionEvent
import android.widget.ImageView

object FilterUtils {

    /**
     * 点击效果
     */
    fun addClickAlpha(view: ImageView) {
        view.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
//                    view.background.alpha = 155
                    setFilter(view)
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
//                    view.background.alpha = 255
                    removeFilter(view)
                }
            }
            return@setOnTouchListener false
        }
    }

    /**
     * 设置滤镜
     */
    private fun setFilter(view: ImageView) {
        //先获取设置的src图片
        var drawable: Drawable? = view?.getDrawable()
        //当src图片为Null，获取背景图片
        if (drawable == null) {
            drawable = view?.getBackground()
        }
        if (drawable != null) {
            //设置滤镜
            drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
        }
    }

    /**
     * 清除滤镜
     */
   private fun removeFilter(view: ImageView) {
        //先获取设置的src图片
        var drawable: Drawable? = view?.getDrawable()
        //当src图片为Null，获取背景图片
        if (drawable == null) {
            drawable = view?.getBackground()
        }
        drawable?.clearColorFilter()
    }
}