图片点击之穿透点击

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.graphics.drawable.DrawableContainer.DrawableContainerState;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class TriangleButton extends Button {

    private Bitmap mBitmap;

    public TriangleButton(Context context) {
        this(context, null);
    }

    public TriangleButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TriangleButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (mBitmap == null) {
                mBitmap = getBackgroundBitmap();
            }
            if (mBitmap == null) {
                return super.dispatchTouchEvent(event);
            }
            try {
                int pixel = mBitmap.getPixel((int) event.getX(), (int) event.getY());
                if (pixel == 0) {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return super.dispatchTouchEvent(event);
    }

    private Bitmap getBackgroundBitmap() {
        Drawable drawable = getBackground();
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        if (drawable instanceof StateListDrawable) {
            StateListDrawable stateListDrawable = (StateListDrawable) drawable;
            ConstantState constantState = stateListDrawable.getConstantState();
            if (constantState instanceof DrawableContainerState) {
                DrawableContainerState drwblContainerState = (DrawableContainerState) constantState;
                Drawable[] drawables = drwblContainerState.getChildren();
                if (drawables == null || drawables.length < 1) {
                    return null;
                }
                for (Drawable drwbl : drawables) {
                    if (drwbl instanceof BitmapDrawable) {
                        return ((BitmapDrawable) drwbl).getBitmap();
                    }
                }
            }
        }

        return null;
    }
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011821032/article/details/52352701
文章标签: 图片 点击
个人分类: Android爬坑路
上一篇图片点击之区域点击
下一篇expandableListView点击高亮
想对作者说点什么? 我来说一句

imageView点击穿透事件示例

2016年09月08日 3KB 下载

没有更多推荐了,返回首页

关闭
关闭