«

Android 多个ImageView图片层叠透明区域点击事件穿透

时间:2024-3-2 19:18     作者:韩俊     分类: Android



经常用到多个透明图片层叠,但又需要获取不同图片的点击事件,本文实现图片透明区域穿透点击事件。

实现人体各个部位点击

内部类

   private class MyOnTouchListener implements OnTouchListener {

        private ImageView touchImageView;
        private Bitmap touchBitmap;
        private int normal_iv;
        private int press_iv;

        public MyOnTouchListener(ImageView touchImageView, Bitmap touchBitmap,
                int normal_iv, int press_iv) {
            super();
            this.touchImageView = touchImageView;
            this.touchBitmap = touchBitmap;
            this.normal_iv = normal_iv;
            this.press_iv = press_iv;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            LogUtils.i(TAG, "onTouch。。。");
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    LogUtils.i(TAG, "ACTION_DOWN ");
                    downOrMove(event);
                    break;
                case MotionEvent.ACTION_MOVE:
                    LogUtils.i(TAG, "ACTION_MOVE ");
                    downOrMove(event);
                    break;
                case MotionEvent.ACTION_UP:
                    LogUtils.i(TAG, "ACTION_UP ");
                    touchImageView.setImageResource(normal_iv);
                    break;
                default:
                    break;
            }

             return false;
        }

        private void downOrMove(MotionEvent event) {
            Matrix inverse = new Matrix();
            touchImageView.getImageMatrix().invert(inverse);
            float[] touchPoint = new float[] { event.getX(), event.getY() };
            inverse.mapPoints(touchPoint);
            int xCoord = Integer.valueOf((int) touchPoint[0]);
            int yCoord = Integer.valueOf((int) touchPoint[1]);

            if((xCoord >= 0 && xCoord < touchBitmap.getWidth()) && (yCoord >=0 &&  yCoord < touchBitmap.getHeight())) {
                if (touchBitmap.getPixel(xCoord, yCoord) == 0) {
                    touchImageView.setImageResource(normal_iv);
                } else {
                    touchImageView.setImageResource(press_iv);
                }
            }
        }
    }
activity中实现

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                LogUtils.i(TAG, "Activity ACTION_DOWN ");
                break;
            case MotionEvent.ACTION_MOVE:
                LogUtils.i(TAG, "Activity ACTION_MOVE ");
                break;
            case MotionEvent.ACTION_UP:
                LogUtils.i(TAG, "Activity ACTION_UP ");
                cancelAllIv();
                break;
        default:
            break;
    }
        return super.onTouchEvent(event);
    }


        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐