import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams; public class MainActivity extends Activity { View view;
public static final int DRAG = 1;
public static final int SCALE = 2;
int mode = 1;
float lengthOld = 1;//初始化两指之间原长 //初始化圆点高宽,java代码中操作的宽高都是像素值,dp*density转成px
int width = 40;
int height = 40; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Log.e("TAG", "像素密度:"+getResources().getDisplayMetrics().density);
view = findViewById(R.id.view);
} /**
* 在MainActivity中画一个圆
* Activity重写onTouchEvent,触摸监听
* getRawX(),getRawY()是获取手机屏幕上的点到屏幕左上角顶点的距离
* getX(),getY()是获取视图坐标,子视图在父视图中的位置
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
//记录坐标,圆点距离视图顶点
int x = (int) event.getX();
int y = (int) event.getY(); //多指触控
//获取事件源,并通过event.getActionMasked()加入多点触控支持
switch (event.getAction() & event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
//单指移动
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
//多指缩放
Log.e("TAG", "多指移动");
mode = SCALE;
//计算两指间开始的原长
lengthOld = calculation(event);
break;
case MotionEvent.ACTION_UP:
lengthOld = 1;//复位
break;
case MotionEvent.ACTION_MOVE:
if(mode == DRAG){
//单指,直接设置坐标
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
params.setMargins(x, y, 0, 0);
view.setLayoutParams(params); }else{
//两指缩放,要计算缩放比例
float scale = calculation(event) / lengthOld;
width = (int) (view.getWidth() * scale);
height = (int) (view.getHeight() * scale); FrameLayout.LayoutParams params = (LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
break;
} return true;
} private float calculation(MotionEvent event) { float x1 = event.getX();
float x2 = event.getX(1);
float y1 = event.getY();
float y2 = event.getY(1); return (float) Math.sqrt(Math.pow((x1-x2), 2)+Math.pow((y1-y2), 2));
}
}

xml中设置

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > <View
android:id="@+id/view"
android:layout_width="20dp"
android:layout_height="20dp"
android:background="@drawable/oval" /> </FrameLayout>
05-08 08:14