if (displayLink) {
[displayLink invalidate];
displayLink = nil;
}
CGPoint p = [panGestureRecognizer translationInView:self];
switch (panGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
{
_lastPoint = [panGestureRecognizer translationInView:self];
break;
}
case UIGestureRecognizerStateChanged:
{
int dx = (int) (p.x - _lastPoint.x);
int dy = (int) (p.y - _lastPoint.y);
[self.contentView TransitionWithXValue:dx*_transitionFactor andYValue:dy*_transitionFactor];
_lastPoint.x = p.x;
_lastPoint.y = p.y;
break;
}
case UIGestureRecognizerStateEnded: {
velocity = [sender velocityInView:self];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
float slideFactor = 0.1 * slideMult;
updateCount = slideFactor * 120 + 1;
currentCount = 0;
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateView)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
default:
break;
}
-(void)updateView {
currentCount++;
//40ms
if (currentCount>updateCount || currentCount>40) {
[displayLink removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[displayLink invalidate];
displayLink = nil;
}else{
//速度衰减以开方的比例递增
float p = sqrtf(currentCount);
CGPoint point = CGPointMake(velocity.x/p, velocity.y/p);
int dx = point.x *0.1;
int dy = point.y *0.1;
[self.contentView TransitionWithXValue:dx andYValue:dy];
}
}
CADisplayLink ,定时器的一种。以屏幕刷新率为触发时间,即1/60。
velocity.x为x轴速度,即点/秒。
p为速度衰减比例,以currentCount递增即越来越慢,但以currentCount递增过快且不平滑,故取开方。
网友评论