iOS - 设置最小/最大限制以进行平移

时间:2013-08-22 13:12:51

标签: ios uiview uigesturerecognizer zooming uipangesturerecognizer

我有一个UIViewController,它调用UIView:

我正在使用UIPinchGesture放大UIView 根据缩放的比例

,我想要做的是限制用户可以平移多少

即。     “currentScale”

目前我正在使用的代码不允许平移,当currentScale(Amount zoom)小于1.1x缩放时,但如果它很好1.1它允许pannin,但是这允许UIView被平移和移动没有界限,我希望能够将其平移量设置为其边界:当前代码

if (currentScale <= 1.1f) {
    // Use this to animate the position of your view to where you want
    [UIView animateWithDuration: 0.5
                          delay: 0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGPoint finalPoint = CGPointMake(self.view.bounds.size.width/2,
                                                          self.view.bounds.size.height/2);
                         recognizer.view.center = finalPoint; }
                     completion:nil];
}

else {
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
}

有些方向,非常感谢 - 谢谢你!

1 个答案:

答案 0 :(得分:1)

免责声明 - 这可能不是最好的方法,但这就是我解决它的方法:

1)通过测量视图中心偏离其原始位置的方式,我推断出需要在5个不同的缩放点在X 0r Y方向上平移多少:

2)我使用NSLog进行大部分测量) - 我对结果进行了标准化 - 并将其绘制成excel - 绘制了一条曲线 - 并得到了Zoom level Vs View.center的等式

3)然后我根据我得到的等式简单地编码平移手势:

代码如下(xMax,xMin,yMax,yMin都绘制了方程式,公共因子是“zoomScale”

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {

//dont pan if zoomscale = 1 (this indicates no zooming)
if (zoomScale <= 1.0f) {
    return;
}

//panning gesture began / state changes 
if ([recognizer state] == UIGestureRecognizerStateBegan ||
    [recognizer state] == UIGestureRecognizerStateChanged) {

    //detect translation gesture 
    translation = [recognizer translationInView:self.view];
    //newCenter is a variable detecting how your translation gesture would efect your view's center 
    CGPoint newCenter = CGPointMake(recognizer.view.center.x + translation.x,
                                    recognizer.view.center.y + translation.y);

    //Check whether boundary conditions are met 
    BOOL inBounds = (newCenter.y >= yMin && newCenter.y <= yMax &&
                     newCenter.x >= xMin && newCenter.x <= xMax);

    if  (inBounds) {
        //if boundary conditions met : translate your view 
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:self.view];
    }
} 

希望这可以帮助那里的人:不是你必须声明你必须在viewDidLoad方法中启动(声明)UIPanGestureRecognizer才能使其工作