在iOS中按点偏移从中心移动图像
Posted
技术标签:
【中文标题】在iOS中按点偏移从中心移动图像【英文标题】:move image by point offset from center in iOS 【发布时间】:2013-01-19 06:47:21 【问题描述】:我正在使用 UIPanGesture 在 iPhone 屏幕上移动图像。有些图像很小,当您在手指周围移动它们时,会遮挡您对图像本身的看法。我想在移动图像的同时设置图像的中心,以便图像中心实际上是触摸位置前面的 10 个点,而不是将其设置为触摸位置。
我测试了下面的内容,但很快意识到它反复从 Y 中减去 10,使图像离触摸位置越来越远,最终离开屏幕,而不是保持恒定的 10 点偏移。
我应该怎么做?
- (void) TestGestureMethod:(UIPanGestureRecognizer *) panGesture
CGPoint translation = [panGesture translationInView:self.view];
switch (panGesture.state)
case UIGestureRecognizerStateBegan:
[self.view bringSubviewToFront:testObject];
break;
case UIGestureRecognizerStateChanged:
testObject.center = CGPointMake(testObject.center.x + translation.x,
testObject.center.y + translation.y);
testObject.center = CGPointMake(testObject.center.x, testObject.center.y - 10);
break;
case UIGestureRecognizerStateEnded:
break;
[panGesture setTranslation:CGPointZero inView:self.view];
【问题讨论】:
【参考方案1】:由于您不是翻译图像而是手动设置其中心,您是否考虑过使用 UIGestureRecognizer locationInView: 而不是 translationInView:?
你可以做这样的事情......
- (void)TestGestureMethod:(UIPanGestureRecognizer *)panGesture
CGPoint location = [panGesture locationInView:self.view];
switch (panGesture.state)
...
case UIGestureRecognizerStateChanged:
testObject.center = CGPointMake(location.x, location.y - 10);
break;
...
这应该会导致图像中心始终位于触摸点下方 10 点处。
【讨论】:
有没有办法为第一次拖动时对象的突然移动设置动画?也许调整它的大小,或者添加一个弹簧动作?【参考方案2】:试试这个:
- (void) TestGestureMethod:(UIPanGestureRecognizer *) panGesture
CGPoint translation = [panGesture translationInView:self.view];
switch (panGesture.state)
case UIGestureRecognizerStateBegan:
[self.view bringSubviewToFront:testObject];
testObject.center = CGPointMake(testObject.center.x, testObject.center.y - 10);
break;
case UIGestureRecognizerStateChanged:
testObject.center = CGPointMake(testObject.center.x + translation.x,
testObject.center.y + translation.y);
break;
case UIGestureRecognizerStateEnded:
break;
[panGesture setTranslation:CGPointZero inView:self.view];
【讨论】:
【参考方案3】:试试这个,这解决了你的问题:
- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer
UIView *piece = [gestureRecognizer view];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged)
CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
希望对你有帮助。
【讨论】:
以上是关于在iOS中按点偏移从中心移动图像的主要内容,如果未能解决你的问题,请参考以下文章
iOS - 通过动画将搜索栏从中心移动到导航栏下方(Swift)