在iOS中通过点偏移从中心移动图像

时间:2013-01-19 06:47:21

标签: iphone ios uipangesturerecognizer

使用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];
}

3 个答案:

答案 0 :(得分:4)

由于您没有翻译图片而是手动设置其中心,您是否考虑过使用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点处。

答案 1 :(得分:0)

试试这个:

- (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];
}

答案 2 :(得分:0)

试试这个,这解决了你的问题:

- (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]];
    }
}

我希望这会对你有所帮助。