-->

Pinch to Zoom - Android Studio Tutorial (Gestures)

tienanh-it Hello, today I will introduce you to pinch to zoom on android.
First create the activity_main layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"    android:layout_width="match_parent"    android:layout_height="match_parent">
    <ImageView        android:id="@+id/imgview"        android:contentDescription="@string/app_name"        android:src="@drawable/demo"        android:scaleType="centerInside"        android:layout_width="200dp"        android:layout_height="200dp" />
</RelativeLayout>
 Next step you create a class Mainactivity.java.
   In the Mainactivity class you create a class  ScaleDector.
package com.anhttvn.demoadmod;

import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    Matrix matrix = new Matrix();
    Float scale =1f;
    ScaleGestureDetector SGD;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imgview);
        SGD = new ScaleGestureDetector(this,new ScaleDector());
    }
    private class ScaleDector extends ScaleGestureDetector.SimpleOnScaleGestureListener{
        @Override        public boolean onScale(ScaleGestureDetector detector) {
            scale = scale * detector.getScaleFactor();
            scale = Math.max(0.1f,Math.min(scale,5f));
            matrix.setScale(scale, scale);
            imageView.setImageMatrix(matrix);
            return true;
        }
    }

    @Override    public boolean onTouchEvent(MotionEvent event) {
        SGD.onTouchEvent(event);
        return true;
    }
}

Disqus Comments