1.Activity
Package com.fit.touchimage;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Matrix;
Import Android.graphics.PointF;
Import Android.os.Bundle;
Import Android.util.FloatMath;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.view.View.OnTouchListener;
Import Android.view.ViewGroup.MarginLayoutParams;
Import Android.widget.ImageView;
public class Mainactivity extends Activity implements Ontouchlistener {
/** called when the activity is first created. */
Zoom in and Zoom out
Matrix matrix=new Matrix ();
Matrix savedmatrix=new Matrix ();
PointF start=new PointF ();
PointF mid=new PointF ();
float olddist;
Private ImageView Myimageview;
Mode
static final int none=0;
static final int drag=1;
static final int zoom=2;
int mode=none;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
myimageview= (ImageView) Findviewbyid (r.id.myimage);
Myimageview.setontouchlistener (this);
}
@Override
public boolean OnTouch (View V, motionevent event) {
ImageView myimageview= (ImageView) v;
Switch (event.getaction () &motionevent.action_mask) {
Set Drag mode
Case Motionevent.action_down:
Matrix.set (Myimageview.getimagematrix ());
Savedmatrix.set (matrix);
Start.set (Event.getx (), event.gety ());
Mode=drag;
Break
Case MOTIONEVENT.ACTION_UP:
Case MOTIONEVENT.ACTION_POINTER_UP:
Mode=none;
Break
Set multi-touch mode
Case Motionevent.action_pointer_down:
Olddist=spacing (event);
if (olddist>10f) {
Savedmatrix.set (matrix);
Midpoint (Mid, event);
Mode=zoom;
}
Break
For drag mode, click Move Picture
Case Motionevent.action_move:
if (Mode==drag) {
Matrix.set (Savedmatrix);
Matrix.posttranslate (Event.getx ()-start.x,event.gety ()-start.y);
}
If zoom mode, tap Touch zoom
else if (mode==zoom) {
Float newdist=spacing (event);
if (newdist>10f) {
Matrix.set (Savedmatrix);
float scale=newdist/olddist;
Set the zoom ratio and the midpoint position of the picture
Matrix.postscale (Scale,scale, MID.X,MID.Y);
}
}
Break
}
Myimageview.setimagematrix (matrix);
return true;
}
Calculate moving distance
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 Midpoint Position
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);
}
}
2. Layout
<?xml version= "1.0" encoding= "Utf-8"?
<linearlayout xmlns:android= "http://schemas.android.com/apk /res/android "
android:orientation=" vertical "android:layout_width=" fill_parent "
android: layout_height= "fill_parent" android:gravity= "center";
<imageview android:layout_width= "Fill_ Parent "
android:layout_height=" fill_parent "android:scaletype=" Matrix "
android:id = "@+id/myimage" android:src= "@drawable/xiaoxiong"/>
</linearlayout>