缩放和移动自定义布局

时间:2018-10-18 09:49:15

标签: android android-layout

我从RelativeLayout扩展了自定义类,以在其上添加scalemove功能。这些功能有效,但我不喜欢它在屏幕上的移动方式,需要帮助来改进它。这是我的代码:

public class GestureRelativeLayout extends RelativeLayout {

    private ScaleGestureDetector mScaleDetector;
    private GestureDetector mGestureDetector;

    public GestureRelativeLayout(Context context) {
        super(context);
        init(context);
    }

    public GestureRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GestureRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mGestureDetector = new GestureDetector(context, new Gesture());
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        mScaleDetector.onTouchEvent(ev);
        mGestureDetector.onTouchEvent(ev);

        return true;
    }

    private class Gesture extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();

            if (Math.abs(diffX) > Math.abs(diffY)) {
                setPivotX(e2.getX());
                setPivotY(e1.getY());

            } else {
                setPivotX(e1.getX());
                setPivotY(e2.getY());
            }

            return true;
        }
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        private float mScaleFactor = 1.f;

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();
            mScaleFactor = Math.max(1f, Math.min(mScaleFactor, 2.0f));

            setScaleX(mScaleFactor);
            setScaleY(mScaleFactor);

            return true;
        }
    }
}

为了在屏幕上移动布局,我扩展了SimpleOnGestureListener类并覆盖了其onScroll方法。因此,当用户缩放视图时,我需要帮助对其进行更改并将其移动到屏幕的右/左/上/下侧。非常感谢您的帮助!

0 个答案:

没有答案