Android 单指触控拖拽,两指触控缩放
1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.util.Log; 4 import android.view.MotionEvent; 5 import android.view.View; 6 import android.view.Window; 7 import android.widget.FrameLayout; 8 import android.widget.FrameLayout.LayoutParams; 9 10 public class MainActivity extends Activity { 11 12 View view; 13 public static final int DRAG = 1; 14 public static final int SCALE = 2; 15 int mode = 1; 16 float lengthOld = 1;//初始化两指之间原长 17 18 //初始化圆点高宽,java代码中操作的宽高都是像素值,dp*density转成px 19 int width = 40; 20 int height = 40; 21 22 @Override 23 protected void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 requestWindowFeature(Window.FEATURE_NO_TITLE); 26 setContentView(R.layout.activity_main); 27 Log.e("TAG", "像素密度:"+getResources().getDisplayMetrics().density); 28 view = findViewById(R.id.view); 29 } 30 31 /** 32 * 在MainActivity中画一个圆 33 * Activity重写onTouchEvent,触摸监听 34 * getRawX(),getRawY()是获取手机屏幕上的点到屏幕左上角顶点的距离 35 * getX(),getY()是获取视图坐标,子视图在父视图中的位置 36 */ 37 @Override 38 public boolean onTouchEvent(MotionEvent event) { 39 //记录坐标,圆点距离视图顶点 40 int x = (int) event.getX(); 41 int y = (int) event.getY(); 42 43 //多指触控 44 //获取事件源,并通过event.getActionMasked()加入多点触控支持 45 switch (event.getAction() & event.getActionMasked()) { 46 case MotionEvent.ACTION_DOWN: 47 //单指移动 48 mode = DRAG; 49 break; 50 case MotionEvent.ACTION_POINTER_DOWN: 51 //多指缩放 52 Log.e("TAG", "多指移动"); 53 mode = SCALE; 54 //计算两指间开始的原长 55 lengthOld = calculation(event); 56 break; 57 case MotionEvent.ACTION_UP: 58 lengthOld = 1;//复位 59 break; 60 case MotionEvent.ACTION_MOVE: 61 if(mode == DRAG){ 62 //单指,直接设置坐标 63 FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height); 64 params.setMargins(x, y, 0, 0); 65 view.setLayoutParams(params); 66 67 }else{ 68 //两指缩放,要计算缩放比例 69 float scale = calculation(event) / lengthOld; 70 width = (int) (view.getWidth() * scale); 71 height = (int) (view.getHeight() * scale); 72 73 FrameLayout.LayoutParams params = (LayoutParams) view.getLayoutParams(); 74 params.width = width; 75 params.height = height; 76 view.setLayoutParams(params); 77 } 78 break; 79 } 80 81 return true; 82 } 83 84 85 private float calculation(MotionEvent event) { 86 87 float x1 = event.getX(); 88 float x2 = event.getX(1); 89 float y1 = event.getY(); 90 float y2 = event.getY(1); 91 92 return (float) Math.sqrt(Math.pow((x1-x2), 2)+Math.pow((y1-y2), 2)); 93 } 94 }
xml中设置
1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent" > 4 5 <View 6 android:id="@+id/view" 7 android:layout_width="20dp" 8 android:layout_height="20dp" 9 android:background="@drawable/oval" /> 10 11 </FrameLayout>