Android ImageView Zoom-in and Zoom-Out

前端 未结 23 1911
死守一世寂寞
死守一世寂寞 2020-11-22 09:31

I want to Zoom-in and Zoom-out an Android ImageView. I tried most of the samples but in all of them the image in the ImageView itself is getting Zoomed-in and Zoomed-out, wh

23条回答
  •  太阳男子
    2020-11-22 10:09

    Try the following:

    package com.example.nwssugeoinformationmobileapplication;
    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.util.FloatMath;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.View.OnTouchListener;
    import android.widget.TabHost;
    import android.widget.TabHost.TabSpec;
    import android.graphics.Matrix;
    import android.graphics.PointF;
    import android.graphics.RectF;
    import android.graphics.drawable.Drawable;
    import android.view.View;
    import android.widget.ImageView;
    public class MainActivity extends Activity implements  OnTouchListener {
    
        private static final String TAG = "Touch";
        Matrix matrix = new Matrix();
        Matrix savedMatrix = new Matrix();
        static final int NONE = 0;
        static final int DRAG = 1;
        static final int ZOOM = 2;
        int mode = NONE;
        PointF start = new PointF();
        PointF mid = new PointF();
        float oldDist = 1f;
    
        private ImageView view;
        private float[] matrixValues = new float[9];
        private float maxZoom;
        private float minZoom;
        private float height;
        private float width;
        private RectF viewRect;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            TabHost th = (TabHost) findViewById (R.id.tabhost);
            th.setup();
    
            TabSpec specs = th.newTabSpec("tag1");
            specs.setContent(R.id.tab1);
            specs.setIndicator("Map");
            th.addTab(specs);
    
    
            specs = th.newTabSpec("tag2");
            specs.setContent(R.id.tab2);
            specs.setIndicator("Search");
            th.addTab(specs);
    
    
            view = (ImageView) findViewById(R.id.imageView1);
            Drawable bitmap = getResources().getDrawable(R.drawable.map);
            view.setImageDrawable(bitmap);
            view.setOnTouchListener(this); 
    
            matrix.setTranslate(1f, 1f);
            view.setImageMatrix(matrix);
    
    
    
        } 
    
    
    
        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
        init();
                }
        }
        private void init() {
            maxZoom = 2;
            minZoom = 1f;
            height = view.getDrawable().getIntrinsicHeight();
            width = view.getDrawable().getIntrinsicWidth();
            viewRect = new RectF(0, 0, view.getWidth(), view.getHeight());
            }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menus, menu);
            return true; 
            }
    
        public boolean onOptionsItemSelected(MenuItem item) {
    
            if(item.getItemId()== R.id.item1){
                Log.d("Tracks", "Track Us was Clicked");
    
                startActivity(new Intent (MainActivity.this, Tracklocation.class ));
                }
    
            if(item.getItemId()== R.id.item2){
                Log.d("Updates", "Updates was Clicked");
    
                startActivity(new Intent (MainActivity.this, Updates.class ));
                }
    
            if(item.getItemId()== R.id.item3){
                Log.d("About Us", "About Us was Clicked");
    
    
                startActivity(new Intent (MainActivity.this, Horoscope.class ));
                }
    
    
            return super.onOptionsItemSelected(item);
    
         }
    
    
        @Override
        public boolean onTouch(View v, MotionEvent rawEvent) {
            ImageView view = (ImageView) v;
            view.setScaleType(ImageView.ScaleType.MATRIX);
            dumpEvent(rawEvent);
        // Handle touch events here...
        switch (rawEvent.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
        savedMatrix.set(matrix);
        start.set(rawEvent.getX(), rawEvent.getY());
        Log.d(TAG, "mode=DRAG");
        mode = DRAG;
        break;
        case MotionEvent.ACTION_POINTER_DOWN:
        oldDist = spacing(rawEvent);
        Log.d(TAG, "oldDist=" + oldDist);
        if (oldDist > 10f) {
        savedMatrix.set(matrix);
        midPoint(mid, rawEvent);
        mode = ZOOM;
        Log.d(TAG, "mode=ZOOM");
        }
        break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
        mode = NONE;
        Log.d(TAG, "mode=NONE");
        break;
        case MotionEvent.ACTION_MOVE:
        if (mode == DRAG) {
        matrix.set(savedMatrix);
        // limit pan
        matrix.getValues(matrixValues);
        float currentY = matrixValues[Matrix.MTRANS_Y];
        float currentX = matrixValues[Matrix.MTRANS_X];
        float currentScale = matrixValues[Matrix.MSCALE_X];
        float currentHeight = height * currentScale;
        float currentWidth = width * currentScale;
        float dx = rawEvent.getX() - start.x;
        float dy = rawEvent.getY() - start.y;
        float newX = currentX+dx;
        float newY = currentY+dy;
        RectF drawingRect = new RectF(newX, newY, newX+currentWidth, newY+currentHeight);
        float diffUp = Math.min(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
        float diffDown = Math.max(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
        float diffLeft = Math.min(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
        float diffRight = Math.max(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
    
        if(diffUp > 0 ){
        dy +=diffUp;
        }
        if(diffDown < 0){
        dy +=diffDown;
        }
        if( diffLeft> 0){
        dx += diffLeft;
        }
        if(diffRight < 0){
        dx += diffRight;
        }
        matrix.postTranslate(dx, dy);
        } else if (mode == ZOOM) {
        float newDist = spacing(rawEvent);
        Log.d(TAG, "newDist=" + newDist);
        if (newDist > 10f) {
        matrix.set(savedMatrix);
        float scale1 = newDist / oldDist;
        matrix.getValues(matrixValues);
        float currentScale = matrixValues[Matrix.MSCALE_X];
        // limit zoom
        if (scale1 * currentScale > maxZoom) {
        scale1 = maxZoom / currentScale;
        } else if (scale1 * currentScale < minZoom) {
        scale1 = minZoom / currentScale;
        }
        matrix.postScale(scale1, scale1, mid.x, mid.y);
        }
        }
        break;
        }
        view.setImageMatrix(matrix);
        return true; 
        }
    
        @SuppressWarnings("deprecation")
        private void dumpEvent(MotionEvent event) {
            String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
            StringBuilder sb = new StringBuilder();
            int action = event.getAction();
            int actionCode = action & MotionEvent.ACTION_MASK;
            sb.append("event ACTION_").append(names[actionCode]);
            if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
            sb.append("(pid ").append(
            action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
            sb.append(")");
            }
            sb.append("[");
            for (int i = 0; i < event.getPointerCount(); i++) {
            sb.append("#").append(i);
            sb.append("(pid ").append(event.getPointerId(i));
            sb.append(")=").append((int) event.getX(i));
            sb.append(",").append((int) event.getY(i));
            if (i + 1 < event.getPointerCount())
            sb.append(";");
            }
            sb.append("]");
            Log.d(TAG, sb.toString());
            }
            /** Determine the space between the first two fingers */
            private float spacing(MotionEvent event) {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return FloatMath.sqrt(x * x + y * y);
            }
            /** Calculate the mid point of the first two fingers */
            @SuppressLint("FloatMath")
            private void midPoint(PointF point, MotionEvent event) {
            float x = event.getX(0) + event.getX(1);
            float y = event.getY(0) + event.getY(1);
            point.set(x / 2, y / 2);
            }
    }
    

提交回复
热议问题