我有一个用户必须在屏幕上拖动的对象。这是一个常规的UIImageView。当前,可以拖动图像,但是在释放图像时,它会停在手指抬起图像的位置。我想要的是创造动量,这样我就可以给图像带来冲动,并且它会滚动直到它反弹到屏幕边缘为止。
我不想像添加物理库之类的东西那么复杂。我想将其保持在最低限度。
我怎么做?你们能指出我一些指导或正确的方向吗?
谢谢。
最佳答案
在不使用任何物理库的情况下执行此操作的一种方法是:
首先在您的类中创建4个实例变量,如下所示:
CFTimeInterval startTime;
CGPoint startPoint;
CGPoint oldPoint;
BOOL imageViewTouched;
在您的
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
方法中要有以下代码:- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouched] anyObject];
// Test to see if the touched view is your image view. If not just return.
if (touch.view != <#yourImageView#>) {
return;
}
startPoint = [touch locationInView:self.view];
oldPoint = startPoint;
startTime = CACurrentMediaTime();
imageViewTouched = YES;
}
对于
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
,请执行以下操作:- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// Fingers were moved on the screen but your image view was not touched in the beginning
if (!imageViewTouched) {
return;
}
UITouch *touch = [[event allTouches] anyObject];
CGPoint newPoint = [touch locationInView:self.view];
<#yourImageView#>.frame = CGRectOffset(<#yourImageView#>.frame, newPoint.x - oldPoint.x, newPoint.y - oldPoint.y);
oldPoint = newPoint;
}
现在为
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
尝试以下操作:- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// Fingers were removed from the screen but your image view was not touched in the beginning
if (!imageViewTouched) {
return;
}
imageViewTouched = NO;
UITouch *touch = [[event allTouches] anyObject];
CGPoint endPoint = [touch locationInView:self.view];
CFTimeInterval endTime = CACurrentMediaTime();
CFTimeInterval timeDifference = endTime - startTime;
// You may play with this value until you get your desired effect
CGFloat maxSpeed = 80;
CGFloat deltaX = 0;
CGFloat deltaY = 0;
if (timeDifference < 0.35) {
deltaX = (endPoint.x - startPoint.x) / (timeDifference * 10);
deltaY = (endPoint.y - startPoint.y) / (timeDifference * 10);
}
if (deltaX > maxSpeed) { deltaX = maxSpeed; }
else if (deltaX < -maxSpeed) { deltaX = -maxSpeed; }
else if (deltaX > -5 && deltaX < 5) { deltaX = 0; }
if (deltaY > maxSpeed) { deltaY = maxSpeed; }
else if (deltaY < -maxSpeed) { deltaY = -maxSpeed; }
else if (deltaY > -5 && deltaY < 5) { deltaY = 0; }
[UIView begginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
<#yourImageView#>.frame = CGRectOffset(<#yourImageView#>.frame, deltaX, deltaY);
[UIView commitAnimations];
}
请让我知道这是否有意义和/或对您有用。干杯!
关于iphone - iPhone-惯性拖动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7787582/