遇到个问题,UI提供了一张图片,但是需要同一张图片点击时要有点击的效果,如何实现呢?立即想到了改变图片的背景透明色
https://www.jianshu.com/p/9cae2250d0ed
https://www.jianshu.com/p/9cae2250d0ed
https://blog.csdn.net/qq_32452623/article/details/79878132
Android-使用 SetColorFilter 神奇地改变图片的颜色
package cn.forestar.mapzone_app.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageButton;
/**
* Created by ZXY on 2019/6/23.
* 同一张图片通过设置滤镜效果实现点击图片
*/
@SuppressLint("AppCompatCustomView")
public class MyImageButton extends ImageButton
{
public MyImageButton(Context context)
{
this(context, null);
}
public MyImageButton(Context context, AttributeSet attrs)
{
this(context, attrs, -1);
}
public MyImageButton(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
setFilter();
break;
case MotionEvent.ACTION_UP:
removeFilter();
break;
}
return true;
}
/**
* 设置滤镜
*/
private void setFilter()
{
//先获取设置的src图片
Drawable drawable = getDrawable();
//当src图片为Null,获取背景图片
if (drawable == null)
{
drawable = getBackground();
}
if (drawable != null)
{
//设置滤镜
drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
;
}
}
/**
* 清除滤镜
*/
private void removeFilter()
{
//先获取设置的src图片
Drawable drawable = getDrawable();
//当src图片为Null,获取背景图片
if (drawable == null)
{
drawable = getBackground();
}
if (drawable != null)
{
//清除滤镜
drawable.clearColorFilter();
}
}
}