Tint / dim drawable on touch

前端 未结 8 1497
别跟我提以往
别跟我提以往 2021-01-31 11:24

The app I\'m currently working on uses a lot of ImageViews as buttons. The graphics on these buttons use the alpha channel to fade out the edges of the button and make them look

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 12:02

    I think this solution is simple enough:

        final Drawable drawable = ... ;
        final int darkenValue = 0x3C000000;
        mButton.setOnTouchListener(new OnTouchListener() {
            Rect rect;
            boolean hasColorFilter = false;
    
            @Override
            public boolean onTouch(final View v, final MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                        drawable.setColorFilter(darkenValue, Mode.DARKEN);
                        hasColorFilter = true;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (rect.contains(v.getLeft() + (int) motionEvent.getX(), v.getTop()
                                + (int) motionEvent.getY())) {
                            if (!hasColorFilter)
                                drawable.setColorFilter(darkenValue, Mode.DARKEN);
                            hasColorFilter = true;
                        } else {
                            drawable.setColorFilter(null);
                            hasColorFilter = false;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        drawable.setColorFilter(null);
                        hasColorFilter = false;
                        break;
                }
                return false;
            }
        });
    

提交回复
热议问题