Wednesday, November 23, 2011

Detect pinch zoom using ScaleGestureDetector

For Android 2.2 (Froyo) android.view.ScaleGestureDetector was added for processing the most commonly requested two-finger gesture: pinch zooming.

Detect pinch zoom using ScaleGestureDetector

package com.exercise.AndroidScaleGestureDetector;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.View;
import android.widget.TextView;

public class AndroidScaleGestureDetectorActivity extends Activity {

TextView scaleGesture;
ScaleGestureDetector scaleGestureDetector;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scaleGesture = (TextView)findViewById(R.id.ScaleGesture);

scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
}

@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
scaleGestureDetector.onTouchEvent(event);
return true;
}

public class simpleOnScaleGestureListener extends
SimpleOnScaleGestureListener {

@Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
scaleGesture.setText(String.valueOf(detector.getScaleFactor()));
return true;
}

@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
scaleGesture.setVisibility(View.VISIBLE);
return true;
}

@Override
public void onScaleEnd(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
scaleGesture.setVisibility(View.INVISIBLE);
}

}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/ScaleGesture"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>


Download the files.

next:
- Scale bitmap according to ScaleGestureDetector



1 comment:

Anonymous said...

Great tutorial. Awesome work man. I mean its not very complex or big, but its good because its upto the mark. :)