ImageView Drag Limitation In Android

前端 未结 5 1655
遇见更好的自我
遇见更好的自我 2021-02-09 06:21

I have an ImageView in a layout and set OnTouchListener on ImageView to drag the ImageView. It\'s working perfectly. My problem is how can I prevent from move ImageView to out o

5条回答
  •  遇见更好的自我
    2021-02-09 06:47

    Add the following parameters to the Touch class:

    private float dx; // postTranslate X distance
    private float dy; // postTranslate Y distance
    private float[] matrixValues = new float[9];
    float matrixX = 0; // X coordinate of matrix inside the ImageView
    float matrixY = 0; // Y coordinate of matrix inside the ImageView
    float width = 0; // width of drawable
    float height = 0; // height of drawable
    

    Modify your code after case MotionEvent.ACTION_MOVE:

    if (mode == DRAG) {
            matrix.set(savedMatrix);
    
            matrix.getValues(matrixValues);
            matrixX = matrixValues[2];
            matrixY = matrixValues[5];
            width = matrixValues[0] * (((ImageView) view).getDrawable()
                                    .getIntrinsicWidth());
            height = matrixValues[4] * (((ImageView) view).getDrawable()
                                    .getIntrinsicHeight());
    
            dx = event.getX() - start.x;
            dy = event.getY() - start.y;
    
            //if image will go outside left bound
            if (matrixX + dx < 0){
                dx = -matrixX;
            }
            //if image will go outside right bound
            if(matrixX + dx + width > view.getWidth()){
                dx = view.getWidth() - matrixX - width;
            }
            //if image will go oustside top bound
            if (matrixY + dy < 0){
                dy = -matrixY;
            }
            //if image will go outside bottom bound
            if(matrixY + dy + height > view.getHeight()){
                dy = view.getHeight() - matrixY - height;
            }
            matrix.postTranslate(dx, dy);   
        }
    

提交回复
热议问题