package com.example.dragscale;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
/**
* 拖拉與多點觸摸
* @author Administrator
*
*/
public class MainActivity extends Activity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)this.findViewById(R.id.imageView);
imageView.setOnTouchListener(new TouchListener());
}
private final class TouchListener implements OnTouchListener
{
private PointF startPointF = new PointF();
private Matrix matrix = new Matrix();
private Matrix currentMatrix = new Matrix();
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN://手指壓下屏幕
currentMatrix.set(imageView.getImageMatrix());//記錄ImageView當前的移動位置
startPointF.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_UP://手指離開屏幕
break;
case MotionEvent.ACTION_MOVE://手指在屏幕移動,該事件會不斷的觸發
float dx = event.getX() - startPointF.x;
float dy = event.getY() - startPointF.y;
matrix.set(currentMatrix);//在上一次的移動位置基礎上進行移動
matrix.postTranslate(dx, dy);
break;
case MotionEvent.ACTION_POINTER_DOWN://當屏幕上已經有觸電(手指),再有一個手指壓下屏幕
break;
case MotionEvent.ACTION_POINTER_UP://有手指離開屏幕,但屏幕還有觸點(手指)
break;
}
imageView.setImageMatrix(matrix);
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
android