这应该是一件非常简单的事情。用户将手指放在屏幕上并将其拖到屏幕上。 onTouch上有两个事件:
现在,我如何计算ACTION_MOVE手势的速度?用户在手势期间将手指拖得更慢或更快,所以我想我需要计算两个中间触摸点之间的速度:lastTouchedPointX,lastTouchedPointY和event.getX(),event.getY()。
以前有人这样做过吗?
答案 0 :(得分:16)
使用标准VelocityTracker
类可以实现您的需求。有关Google的用户输入最佳做法的详细信息,同时跟踪移动here。下面的大多数代码(通过显示每个fling / move的X和Y轴上的速度来演示VelocityTracker
的使用)取自上一个资源链接:
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.VelocityTrackerCompat;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.widget.TextView;
public class MainActivity extends Activity {
private VelocityTracker mVelocityTracker = null;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
mTextView.setText("Move finger on screen to get velocity.");
setContentView(mTextView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int index = event.getActionIndex();
int action = event.getActionMasked();
int pointerId = event.getPointerId(index);
switch (action) {
case MotionEvent.ACTION_DOWN:
if (mVelocityTracker == null) {
// Retrieve a new VelocityTracker object to watch the velocity
// of a motion.
mVelocityTracker = VelocityTracker.obtain();
} else {
// Reset the velocity tracker back to its initial state.
mVelocityTracker.clear();
}
// Add a user's movement to the tracker.
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.addMovement(event);
// When you want to determine the velocity, call
// computeCurrentVelocity(). Then call getXVelocity()
// and getYVelocity() to retrieve the velocity for each pointer ID.
mVelocityTracker.computeCurrentVelocity(1000);
// Log velocity of pixels per second
// Best practice to use VelocityTrackerCompat where possible.
mTextView.setText("X velocity: "
+ VelocityTrackerCompat.getXVelocity(mVelocityTracker,
pointerId)
+ "\nY velocity: "
+ VelocityTrackerCompat.getYVelocity(mVelocityTracker,
pointerId));
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
// Return a VelocityTracker object back to be re-used by others.
mVelocityTracker.recycle();
break;
}
return true;
}
}
答案 1 :(得分:11)
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
oldX = event.getX();
oldY = event.getY();
//start timer
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//long timerTime = getTime between two event down to Up
newX = event.getX();
newY = event.getY();
float distance = Math.sqrt((newX-oldX) * (newX-oldX) + (newY-oldY) * (newY-oldY));
float speed = distance / timerTime;
}
}
答案 2 :(得分:2)
这是一个关于您想要执行此计算的准确程度的问题。
然而,基本程序是获取每个相应的ACTION_DOWN,ACTION_UP对的时间戳并计算差值。
然后你需要确定覆盖的像素。这可以通过简单的三角函数来完成。
如果同时具有时差和覆盖像素,则可以将每个时间速度的像素计算为两个点的平均值(向下和向上)。
当手指在屏幕上移动以获得更好的效果时,您可以为每个点执行此操作。
答案 3 :(得分:0)
Image in Canvas with touch events 从这个例子中得到触摸事件时间&计算时间和获得速度的距离