主要原理是onTouchEvent事件中的参数MotionEvent,它有一个getSize()方法。在一个点的时候,该方法永远返回0,而在两个触电的时候,该方法则根据两点相对位置变化而返回不同的值。我们只需计算出两点之间的距离变化,距离的大小表明我们希望目标变化的趋势。而getX()和getY()方法则永远座落在两触点之间,这样趋势和目标我们都有了。剩下的就是对目标根据趋势进行放大或缩小即可。
下边是根据我前边描述的思路编写的代码:让一个蓝色的圆根据手势放大或者缩小。流感中,代码就不指望太清晰了。
/**
* ...
*
* @author vlinux
*
*/
public class MultiTouchTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
View view = new MultiTouchView(this);
setContentView(view);
}
class MultiTouchView extends View {
private float x1;
private float y1;
private float x2;
private float y2;
public MultiTouchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
float size = event.getSize();
int szi = (int) size;
int dxi = szi >> 12;
int dyit = ((1 << 12) - 1);
int dyi = szi & dyit;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dx = metrics.widthPixels * dxi / (float) dyit;
float dy = metrics.heightPixels * dyi / (float) dyit;
x1 = event.getX();
y1 = event.getY();
x2 = x1 + dx;
y2 = y1 + dy;
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
float r = (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
* (y1 - y2)) / 2;
r = 50 >= r ? 50 : r;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(x1, y1, r, paint);
}
}
}
下边是根据我前边描述的思路编写的代码:让一个蓝色的圆根据手势放大或者缩小。流感中,代码就不指望太清晰了。
/**
* ...
*
* @author vlinux
*
*/
public class MultiTouchTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
View view = new MultiTouchView(this);
setContentView(view);
}
class MultiTouchView extends View {
private float x1;
private float y1;
private float x2;
private float y2;
public MultiTouchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
float size = event.getSize();
int szi = (int) size;
int dxi = szi >> 12;
int dyit = ((1 << 12) - 1);
int dyi = szi & dyit;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dx = metrics.widthPixels * dxi / (float) dyit;
float dy = metrics.heightPixels * dyi / (float) dyit;
x1 = event.getX();
y1 = event.getY();
x2 = x1 + dx;
y2 = y1 + dy;
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
float r = (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
* (y1 - y2)) / 2;
r = 50 >= r ? 50 : r;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(x1, y1, r, paint);
}
}
}