我发现苹果的UIGestureRecognizer设计相当不错,可扩展。
这个想法是分离手势(或交互)的识别和将被触发的动作。
您需要实现基本或抽象的GestureRecognizer类,该类能够基于事件MousePressEvent,MouseReleaseEvent,MouseMoveEvent或MouseWheelEvent等识别某种交互或手势。手势记录器有一个定期报告变化的目标。
例如你很基本的类将是这样的:(对不起我那可怜的半C++伪代码......最近我不使用它那么多)
class Recognizer {
int state; // ex: 0:possible, 1:began, 2:changed, 3:ended/recognized 4:cancelled
protected:
void setTarget(void &theTarget); // or even better a touple, target/method. In this case target is assumed to have a method gestureHandle(Recognizer *r);
virtual void mouserPress() = 0;
virtual void mouserRelease() = 0;
virtual void mouserMove() = 0;
virtual void mouserWheel() = 0;
...
}
如果你想检测用鼠标滑动
class SwipeRecognizer : Recognizer {
int direction; // ex: 0:left2right 1:bottom2top 2:...
private:
void mouserPress() {
state = 0; // possible. You don't know yet is the mouse is going to swipe, simple click, long press, etc.
// save some values so you can calculate the direction of the swipe later
target.gestureHandle(this);
};
void mouserMove() {
if (state == 0) {
state = 1; // it was possible now you know the swipe began!
direction = ... // calculate the swipe direction here
} else if (state == 1 || state == 2) {// state is began or changed
state = 2; // changed ... which means is still mouse dragging
// probably you want to make more checks here like you are still swiping in the same direction you started, maybe velocity thresholds, if any of your conditions are not met you should cancel the gesture recognizer by setting its state to 4
}
target.gestureHandler(this);
};
void mouserRelease() {
if (state == 2) { // is swipping
state = 3; // swipe ended
} else {
state = 4; // it was not swiping so simple cancel the tracking
}
target.gestureHandler(this);
};
void mouserWheel() {
// if this method is called then this is definitely not a swipe right?
state = 4; // cancelled
target.gestureHandler(this);
}
只要确保上述方法在事件发生时被调用,并且他们应该在需要时调用目标。
这是目标会怎么看我说:
class Target {
...
void gestureHandler(Recognizer *r) {
if (r->state == 2) {
// Is swipping: move the opengl camera using some parameter your recognizer class brings
} else if (r->state == 3) {
// ended: stop moving the opengl camera
} else if (r->state == 4) {
// Cancelled, maybe restore camera to original position?
}
}
UIGestureRecognizer的实施是相当不错的,并允许注册多个目标/方法相同识别和几个识别器,以同样的观点。 UIGestureRecognizers有一个委托对象,用于获取有关其他手势识别器的信息,例如,如果两个手势可以同时检测到,或者一旦检测到另一个手势就必须失败等。
一些手势识别器会比其他手势识别器需要更多的覆盖,但是这个大的PRO是它们的输出是相同的:处理器方法通知有关当前状态(和其他信息)。
我觉得是值得考虑看看它
希望它能帮助:)
感谢安东尼您的详细解答。我将尝试实施工厂方法,并结合信号/插槽机制。否则,我看不到如何将openGL拾取连接到实际对象,而这只能给我一些id。 – mike 2012-04-13 06:22:30