【问题标题】:onTouchEvent for children of zoomed ViewGroup缩放 ViewGroup 的子级的 onTouchEvent
【发布时间】:2022-12-30 06:02:04
【问题描述】:

对于我的game Hashi,我想构建一个允许缩放和滚动(两个轴)的自定义 ViewGroup,其中还包含受触摸影响的子项。

我设置了setWillNotDraw(false)并覆盖了draw(Canvas)以使用canvas.scale(..)和canvas.translate(..):

@Override
public void draw(Canvas canvas)
{
    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor, mScaleCenter.x, mScaleCenter.y);
    canvas.translate(mTranslation.x * mScaleFactor, mTranslation.y * mScaleFactor);
    super.draw(canvas);
    canvas.restore();
}

但后来我意识到,onTouchEvent 的 MotionEvent 参数被我设置的翻译值偏移了(所以它们被检测到,就好像容器没有任何缩放或偏移)。

我试图在父ViewGroup中覆盖dispatchTouchEvent并调整事件的坐标。但是MotionEvent是final的,只能通过MotionEvent.obtain(..)来实例化。并且没有obtain的版本可以接受多个坐标,当有不止一根手指按下时。 有什么方法可以修改 MotionEvent 参数,所以我不需要在子视图的 onTouchEvent 方法中进行修改(那样会复杂得多),甚至不需要更好的方法来实现缩放和滚动?

我实现了自己的缩放容器,因为我需要严格控制触摸(孩子们也会听到滑动手势,但需要在第二根手指按下时被拦截)。

【问题讨论】:

    标签: java android zooming


    【解决方案1】:

    不要尝试通过提供坐标来创建新的 MotionEvent。

    复制现有事件,然后使用矩阵对其进行转换。

    例如就像是

    // Matrix used for drawing the view
    Matrix matrix = new Matrix();
    matrix.setScale(scaleFactor, scaleFactor);
    matrix.postTranslate(panX, panY);
    // used with canvas.concat(matrix);
    
    // Matrix for Touch events
    Matrix mappingMatrix = new Matrix();
    // Touch event matrix needs to be inverted
    matrix.invert(mappingMatrix);
    
    // Copy the touch Event that is being mapped
    MotionEvent transformEvent = MotionEvent.obtain(ev);
    // Apply it's event mapping matrix
    transformEvent.transform(mappingMatrix);
    
    

    Obtain copy documentation

    我在我的自定义视图组中做了非常相似的事情,用于将 MotionEvents 缩放到我的 FixedHeaderTableLayout 库中的子项。

    MotionEvent 复制完成here

    【讨论】:

    • 经过几个小时的努力,我让它工作了,多亏了你的投入。如果您有兴趣,请查看我的答案以获得完整的解决方案。
    【解决方案2】:

    因此,对于那些有同样问题的人,我发布了我的解决方案(再次感谢 Andrew your help)。

    更新

    因为我在测试时遇到了输入问题,所以我决定使用onLayout而不是dispatchTouchEvent和draw方法来应用比例因子和平移,因为旧的解决方案只将它应用于绘图和输入检测,但是container 仍然在原来的地方声明了孩子们的位置。这导致浓缩咖啡在错误的地方执行触摸。有了这个解决方案,孩子们就完全抵消了,所以它也适用于测试(可能还有我没有考虑的其他事情)。

    笔记这两种解决方案仅在您嵌入(一个)与父级尺寸匹配的其他布局容器时才有效。 如果你想改变它,你需要改变onLayout的实现。

    public class ZoomContainer extends ViewGroup
    {
        /**
         * Limit the maximum/minimum scrolling to prevent scrolling the container,
         * so that no more children are visible.
         * The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
         */
        protected float mTranslationBounds = 0.1f;
        /**
         * The translation to be applied to the container
         */
        protected PointF mTranslation;
        /**
         * The the current zoom factor.
         * It is initialized with a value smaller than 1, to append some empty space around the view.
         */
        protected float mScaleFactor = 0.95f;
        /**
         * The minimum scale factor to prevent endless zooming
         */
        protected float mScaleFactorMin = 0.8f;
        /**
         * The maximum scale factor to prevent endless zooming.
         */
        protected float mScaleFactorMax = 5.0f;
        /**
         * Used to indicate, whether or not this is the first touch event, which has no differences yet.
         */
        protected boolean mIsTouchStarted = false;
        /**
         * Distance of the fingers from the last touch event
         */
        protected float mStartDistance = 0;
        /**
         * Center of the two fingers from the last touch event.
         */
        protected PointF mStartTouchPoint = new PointF(0, 0);
    
        public ZoomContainer(Context context)
        {
            super(context);
        }
    
        public ZoomContainer(Context context, @Nullable AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        public ZoomContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
        {
            super(context, attrs, defStyleAttr);
        }
    
        /**
         * Cancel all child touch events, if there is more than one finger down.
         */
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev)
        {
            boolean intercept = ev.getPointerCount() > 1;
            if (intercept)
            {
                Log.d("TableView", "Intercepted");
                mIsTouchStarted = false;
            }
            return intercept;
        }
    
        protected void initializeTranslation()
        {
            if (mTranslation == null)
            {
                mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
                        getHeight() * (1 - mScaleFactor) / 2f);
                Log.d("TableView", "Translation: " + mTranslation);
            }
        }
    
        /**
         * Calculate the new zoom and scroll respecting the difference to the last touch event.
         */
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mIsTouchStarted = false;
                    return true;
            }
            if (event.getPointerCount() <= 1)
            {
                mIsTouchStarted = false;
                return true;
            }
            float[] currentPointArray = new float[]{event.getX(0),
                    event.getY(0),
                    event.getX(1),
                    event.getY(1)};
            float currentFingerDistance = getDistance(currentPointArray[0],
                    currentPointArray[1],
                    currentPointArray[2],
                    currentPointArray[3]);
            // Read the current center of the fingers to determine the the new translation
            PointF currentPoint = getPoint(currentPointArray[0],
                    currentPointArray[1],
                    currentPointArray[2],
                    currentPointArray[3]);
            if (mIsTouchStarted)
            {
                // 1 / oldScaleFactor - 1 / newScaleFactor is required to respect the relative translation,
                // when zooming (translation is always from the upper left corner,
                // but zooming should be performed centered to the fingers)
                float scaleFactorDifference = 1f / mScaleFactor;
                mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentFingerDistance / mStartDistance - 1));
                scaleFactorDifference -= 1f / mScaleFactor;
                // Add the finger scroll since the last event to the current translation.
                PointF newTranslation = new PointF(mTranslation.x + (currentPoint.x - mStartTouchPoint.x) / mScaleFactor,
                        mTranslation.y + (currentPoint.y - mStartTouchPoint.y) / mScaleFactor);
                // Add the current point multiplied with the scale difference to make sure,
                // zooming is always done from the center of the fingers. Otherwise zooming would always be
                // applied from the upper left edge of the screen.
                newTranslation.x -= currentPoint.x * scaleFactorDifference;
                newTranslation.y -= currentPoint.y * scaleFactorDifference;
                mTranslation = getBoundTranslation(newTranslation);
            }
            mStartTouchPoint = currentPoint;
            mStartDistance = currentFingerDistance;
            mIsTouchStarted = true;
            requestLayout();
            return true;
        }
    
        protected float getBoundValue(float value, float min, float max)
        {
            return Math.min(Math.max(value, min), max);
        }
    
        protected PointF getBoundTranslation(PointF translation)
        {
            translation.x = getBoundValue(translation.x,
                    -(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
                    getWidth() * mTranslationBounds);
            translation.y = getBoundValue(translation.y,
                    -(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
                    getHeight() * mTranslationBounds);
            return translation;
        }
    
        protected float getBoundScaleFactor(float scaleFactor)
        {
            return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
        }
    
        protected PointF getPoint(float x1, float y1, float x2, float y2)
        {
            return new PointF(getCenter(x1, x2), getCenter(y1, y2));
        }
    
        protected float getCenter(float position1, float position2)
        {
            return (position1 + position2) / 2f;
        }
    
        protected float getDistance(float x1, float y1, float x2, float y2)
        {
            float distanceX = Math.abs(x1 - x2);
            float distanceY = Math.abs(y1 - y2);
            return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b)
        {
            float width = (r - l);
            float height = (b - t);
            if (width <= 0 || height <= 0)
            {
                return;
            }
            initializeTranslation();
            final int childCount = getChildCount();
            l = (int) (mTranslation.x * mScaleFactor);
            r = (int) ((width + mTranslation.x) * mScaleFactor);
            t = (int) (mTranslation.y * mScaleFactor);
            b = (int) ((height + mTranslation.y) * mScaleFactor);
    
            for (int i = 0; i < childCount; i++)
            {
                View child = getChildAt(i);
                child.layout(l, t, r, b);
            }
        }
    }
    

    旧的解决方案

    使用dispatchTouchEvent 和draw 方法来应用比例因子和翻译:

    public class ZoomContainer extends ViewGroup
    {
        /**
         * Limit the maximum/minimum scrolling to prevent scrolling the container, 
         * so that no more children are visible. 
         * The value is relative to the size of the container (so 0.1 means 10% of the size of this container)
         */
        protected float mTranslationBounds = 0.1f;
        /**
         * The translation to be applyed to the container
         */
        protected PointF mTranslation;
        /**
         * The the current zoom factor. You might initialze it to a value smaller than 1, if you want to add some padding in the beginning.
         */
        protected float mScaleFactor = 1f;
        /**
         * The minimum scale factor to prevent endless zooming
         */
        protected float mScaleFactorMin = 0.8f;
        /**
         * The maximum scale factor to prevent endless zooming.
         */
        protected float mScaleFactorMax = 4f;
        /**
         * Used to indicate, whether or not this is the first touch event, which has no differences yet.
         */
        protected boolean mIsTouchStarted = false;
        /**
        * Distance of the fingers from the last touch event
        */
        protected float mStartDistance = 0;
        /**
         * Center of the two fingers from the last touch event.
         */
        protected PointF mStartTouchPoint = new PointF(0, 0);
    
        public ZoomContainer(Context context)
        {
            super(context);
            setWillNotDraw(false);
        }
    
        public ZoomContainer(Context context, @Nullable AttributeSet attrs)
        {
            super(context, attrs);
            setWillNotDraw(false);
        }
    
        public ZoomContainer(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
        {
            super(context, attrs, defStyleAttr);
            setWillNotDraw(false);
        }
    
        @Override
        public void draw(Canvas canvas)
        {
            canvas.save();
            canvas.concat(createDrawMatrix());
            super.draw(canvas);
            canvas.restore();
        }
    
        /**
        * Cancel all child touch events, if there is more than one finger down.
        */
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev)
        {
            boolean intercept = ev.getPointerCount() > 1;
            if (intercept)
            {
                mIsTouchStarted = false;
            }
            return intercept;
        }
    
        /**
         * Creates the transformation matrix for drawing and converting touch coordinates
         */
        protected Matrix createDrawMatrix()
        {
            // Make sure children are centered, if initial scroll factor is not 1.
            if (mTranslation == null)
            {
                mTranslation = new PointF(getWidth() * (1 - mScaleFactor) / 2f,
                        getHeight() * (1 - mScaleFactor) / 2f);
            }
            // Matrix used for drawing the view
            Matrix matrix = new Matrix();
            matrix.setScale(mScaleFactor, mScaleFactor);
            matrix.postTranslate(mTranslation.x, mTranslation.y);
            return matrix;
        }
    
        /**
         * Transform the touch coordinates according to the current zoom and scroll,
         * for children to get the appropriate ones.
         */
        @Override
        public boolean dispatchTouchEvent(MotionEvent ev)
        {
            // Matrix for Touch events
            Matrix mappingMatrix = new Matrix();
            // Touch event matrix needs to be inverted
            createDrawMatrix().invert(mappingMatrix);
    
            // Copy the touch Event that is being mapped
            MotionEvent transformEvent = MotionEvent.obtain(ev);
            // Apply it's event mapping matrix
            transformEvent.transform(mappingMatrix);
    
            boolean handled = super.dispatchTouchEvent(transformEvent);
            transformEvent.recycle();
            return handled;
        }
    
        /**
         * Calculate the new zoom and scroll respecting the difference to the last touch event.
         */
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mIsTouchStarted = false;
                    return true;
            }
            // 
            if (event.getPointerCount() <= 1)
            {
                mIsTouchStarted = false;
                return true;
            }
            float[] currentPointArray = new float[]{event.getX(0),
                    event.getY(0),
                    event.getX(1),
                    event.getY(1)};
            float currentDistance = mScaleFactor * getDistance(currentPointArray[0],
                    currentPointArray[1],
                    currentPointArray[2],
                    currentPointArray[3]);
            Matrix transformation = createDrawMatrix();
            transformation.mapPoints(currentPointArray);
            PointF currentPoint = getPoint(currentPointArray[0],
                    currentPointArray[1],
                    currentPointArray[2],
                    currentPointArray[3]);
            if (mIsTouchStarted)
            {
                float scaleFactorDifference = mScaleFactor;
                mScaleFactor = getBoundScaleFactor(mScaleFactor + (currentDistance / mStartDistance - 1));
                scaleFactorDifference -= mScaleFactor;
                PointF newTranslation = new PointF(mTranslation.x + currentPoint.x - mStartTouchPoint.x,
                        mTranslation.y + currentPoint.y - mStartTouchPoint.y);
                newTranslation.x += currentPoint.x * scaleFactorDifference;
                newTranslation.y += currentPoint.y * scaleFactorDifference;
                mTranslation = getBoundTranslation(newTranslation);
            }
            mStartTouchPoint = currentPoint;
            mStartDistance = currentDistance;
            mIsTouchStarted = true;
            invalidate();
            return true;
        }
    
        protected float getBoundValue(float value, float min, float max)
        {
            return Math.min(Math.max(value, min), max);
        }
    
        protected PointF getBoundTranslation(PointF translation)
        {
            translation.x = getBoundValue(translation.x,
                    -(getWidth() * (mScaleFactor - 1) + getWidth() * mTranslationBounds),
                    getWidth() * mTranslationBounds);
            translation.y = getBoundValue(translation.y,
                    -(getHeight() * (mScaleFactor - 1) + getHeight() * mTranslationBounds),
                    getHeight() * mTranslationBounds);
            return translation;
        }
    
        protected float getBoundScaleFactor(float scaleFactor)
        {
            return getBoundValue(scaleFactor, mScaleFactorMin, mScaleFactorMax);
        }
    
        protected PointF getPoint(float x1, float y1, float x2, float y2)
        {
            return new PointF(getCenter(x1, x2), getCenter(y1, y2));
        }
    
        protected float getCenter(float position1, float position2)
        {
            return (position1 + position2) / 2f;
        }
    
        protected float getDistance(float x1, float y1, float x2, float y2)
        {
            float distanceX = Math.abs(x1 - x2);
            float distanceY = Math.abs(y1 - y2);
            return (float) Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b)
        {
            final int childCount = getChildCount();
            for (int i = 0; i < childCount; i++)
            {
                View child = getChildAt(i);
                child.layout(0, 0, r - l, b - t);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多