简体   繁体   中英

Android translation in relation to scale

I have two layouts. One (A) has a ScaleGestureDetector active on it's contents to handle a PinchZoom functionality while the other (B) has dynamically added ImageViews known as Markers. B sits perfectly on top of A with mirrored alignments and sizes.

When a user zooms in on A, I want the Markers on B to translate in a manner that they remain fixed on the points they were on relative to A. For example, if a user places a Marker on a point of interest (POI) on A, and zooms into a different point, the Marker should remain pinned on the POI.

Currently I'm using the below code for every ScaleGestureDetector instance/action/run:

    float[] values = new float[9];
    trans.getValues(values);
    float transx = values[Matrix.MTRANS_X];
    float transy = values[Matrix.MTRANS_Y];
    float scalex = values[Matrix.MSCALE_X];
    float scaley = values[Matrix.MSCALE_Y];
    float scale = (float) Math.sqrt(scalex * scalex + scaley * scaley);
    focusX = transx - focusX;
    focusY = transy - focusY;
    transx = focusX;
    transy = focusY;
    float markerX = marker.getX();
    float markerY = marker.getY();

    if(markerX > startPoint.x) {
        marker.setTranslationX((-transx/scale) + (-transx%scale));
    }else if(markerX < startPoint.x) {
        marker.setTranslationX((transx/scale) + (transx%scale));
    }
    if(markerY > startPoint.y) {
        marker.setTranslationY((-transy/scale) + (-transy%scale));
    }else if(markerY < startPoint.y) {
        marker.setTranslationY((transy/scale) + (transy%scale));
    }

Where trans is the Matrix used to perform postScales on A's contents and focusX and focusY are merely used to prevent cumulative build-up of the translation values. startPoint is the point of first contact, defined in the MotionEvent.ACTION_DOWN case.

My problem is that the translation becomes progressively "unhinged" when the users zooms in further away from the markers. Larger zoom gestures also cause the Markers to float away from their designated points. For clarity, they get closer to the zoom point and move away from the POI.

I suspect the translation amount at the bottom of the code segment is missing something, likely relative to the size of the layouts.

If I were you, I would take the following approach:

  1. Find the markers position at the start of the movement.
  2. Find the math to correctly identify where the marker should be at any point along the movement.
  3. Use the setX and setY to set it directly to that point.

That will avoid any floating point uncertainties that might arise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM