1. 程式人生 > >Android:通過濾鏡實現點選圖片變暗效果

Android:通過濾鏡實現點選圖片變暗效果

package com.linj.camera.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ImageView;

/** * @ClassName: FilterImageView * @Description: 點選時顯示明暗變化(濾鏡效果)的ImageView * @author LinJ * @date 2015-1-6 下午2:13:46 * */ public class FilterImageView extends ImageView implements GestureDetector.OnGestureListener{ /** 監聽手勢*/ private GestureDetector mGestureDetector;
public FilterImageView(Context context, AttributeSet attrs) { super(context, attrs); mGestureDetector=new GestureDetector(context, this); } @Override public boolean onTouchEvent(MotionEvent event) { //在cancel裡將濾鏡取消,注意不要捕獲cacncel事件,mGestureDetector裡有對cancel的捕獲操作
//在滑動GridView時,AbsListView會攔截掉Move和UP事件,直接給子控制元件返回Cancel if(event.getActionMasked()== MotionEvent.ACTION_CANCEL){ removeFilter(); } return mGestureDetector.onTouchEvent(event); } /** * 設定濾鏡 */ 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(); } } @Override public boolean onDown(MotionEvent e) { setFilter(); //這裡必須返回true,表示捕獲本次touch事件 return true; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { removeFilter(); performClick(); return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onLongPress(MotionEvent e) { //長安時,手動觸發長安事件 performLongClick(); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub return false; } }