遇到個問題,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();
}
}
}