1
我有一個對象,用戶必須拖動屏幕。這是一個普通的UIImageView。目前,圖像可以被拖動,但是當您釋放圖像時,它會停止在您的手指擡起圖像的位置。我想要創造的勢頭,所以我可以給圖像一個衝動,它會滾動,直到它彈起屏幕邊緣。iPhone - 慣性拖動
我不想要像添加物理庫和類似的東西非常複雜。我想盡可能保持最小。
我該怎麼做?你們能指點我一些教程還是朝着正確的方向發展?
謝謝。
我有一個對象,用戶必須拖動屏幕。這是一個普通的UIImageView。目前,圖像可以被拖動,但是當您釋放圖像時,它會停止在您的手指擡起圖像的位置。我想要創造的勢頭,所以我可以給圖像一個衝動,它會滾動,直到它彈起屏幕邊緣。iPhone - 慣性拖動
我不想要像添加物理庫和類似的東西非常複雜。我想盡可能保持最小。
我該怎麼做?你們能指點我一些教程還是朝着正確的方向發展?
謝謝。
好一個這樣做不使用任何物理庫的方式是這樣的:
首先在你的類創建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];
}
請讓我知道,如果這是有道理的和/或你的作品。乾杯!
哇!!!!!!!!!!!!!!太棒了,謝謝!你是男人! – SpaceDog