ios - 我怎样才能像在谷歌地图中那样缩放

标签 ios objective-c uipinchgesturerecognizer

我正在开发一款带有某些游戏场的游戏,该游戏场是在某些 View 中绘制的。我的游戏领域总是相对于他的中心绘制,所以我只是简单地捏一下

- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
if ((gesture.state == UIGestureRecognizerStateChanged) ||
    (gesture.state == UIGestureRecognizerStateEnded)) {
    self.gameBoardGridView.scale *= gesture.scale; // adjust our scale

    gesture.scale = 1;  
}

平移

-(void)pan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translatedPoint = [recognizer translationInView:self.gameBoardGridView];


self.gameBoardGridView.gridCenter = CGPointMake(self.gameBoardGridView.gridCenter.x + translatedPoint.x, self.gameBoardGridView.gridCenter.y + translatedPoint.y);

[recognizer setTranslation:CGPointMake(0, 0) inView:self.gameBoardGridView];
}

但我需要其他类型的变焦。当您放下两根手指然后移动其中一根时,场会像它应该的那样扩展(放大),但手指下方的像素不再位于手指下方。图像从图像中心开始缩放,而不是两根手指之间的中点。

我尝试了很多例子,但没有一个像我想要的那样工作。最后我写了这个,它几乎可以正常工作,但不完全

- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
CGFloat curScale = gesture.scale;

static CGPoint startPoint;

if (gesture.state == UIGestureRecognizerStateBegan) {
    startPoint = [gesture locationInView:self.gameBoardGridView];
}


if ((gesture.state == UIGestureRecognizerStateChanged) ||
    (gesture.state == UIGestureRecognizerStateEnded)) {
    self.gameBoardGridView.scale *= gesture.scale;

    CGFloat widthDelta = self.gameBoardGridView.gridWidth * fabs(gesture.scale - 1) / 3;
    CGFloat heightDelta = self.gameBoardGridView.gridHeight * fabs(gesture.scale - 1) / 3;


    gesture.scale = 1;

    CGPoint lastPoint = self.gameBoardGridView.gridCenter;

    const CGFloat epsilon = 5;

    CGFloat coef = 1.0;
    if(curScale < 1) {
        coef = -1.0;
    }

    if (startPoint.x + epsilon < self.view.frame.size.width / 2) {
            lastPoint.x += widthDelta*coef;
    }
    else if (startPoint.x - epsilon > self.view.frame.size.width / 2) {
            lastPoint.x -= widthDelta*coef;
    }

    if (startPoint.y + epsilon < self.view.frame.size.height / 2) {
            lastPoint.y += heightDelta*coef;
    }
    else if (startPoint.y - epsilon > self.view.frame.size.height / 2) {
            lastPoint.y -= heightDelta*coef;
    }


    self.gameBoardGridView.gridCenter = lastPoint;
}
}

可能还有其他方法可以做到这一点?

最佳答案

缩放的中心是图像的 anchor 。 你要做的就是把 anchor 改成手指的中点,位置,位置。 没有自己尝试购买我在这里看到了一个完整的解决方案,也许它会对你有所帮助 -

https://github.com/robertblackwood/CCPanZoomController

关于ios - 我怎样才能像在谷歌地图中那样缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17429614/

相关文章:

ios - 尝试递归调用-save : on the context aborted when saving Core Data viewContext after CloudKit Record Changed

objective-c - @"Strings"在内存中是如何分配的?

ios - 扩展图像上的捏合手势识别器

objective-c - 我怎样才能更改此代码以使其不违反 MVC 原则?

ios - UIPinchGestureRecognizer 缩放 AVCaptureConnection;不按比例缩小

ios - 使用捏合手势调整 Sprite Kit 节点大小

ios - 具有协议(protocol)问题的 Swift 通用 UIView 子类

iphone - 在 NSUserDefaults 中保存 ALAsset URL

ios - 检查来自 Alamofire 和 Swift 的多个异步响应

objective-c - 自定义基于 View 的 nstableview 调整大小