从角落调整旋转UIView的大小

时间:2014-03-30 01:42:09

标签: ios uiview cgaffinetransform

我有一个UIView selectFrame,有四个角手柄作为子视图。每个角手柄都有一个调用此方法的UIPanGestureRecognizer:

这是我的代码(其中self是selectFrame UIView):

-(void)handleDrag:(UIPanGestureRecognizer *)gesture

{
    UIView *view = gesture.view;
    CGPoint translation = [gesture translationInView:view.superview];

    CGRect frame = self.bounds;

    switch (view.tag) {
        case (DRAG_HANDLE_TAG):  //upper left
            frame.size.width -= translation.x;
            frame.size.height -= translation.y;
            break;
        case (DRAG_HANDLE_TAG+1): //upper right
            frame.size.width += translation.x;
            frame.size.height -= translation.y;
            break;
        case (DRAG_HANDLE_TAG+2): //bottom left
            frame.size.width -= translation.x;
            frame.size.height += translation.y;
            break;
        case (DRAG_HANDLE_TAG+3): //bottom right
            frame.size.width += translation.x;
            frame.size.height += translation.y;
            break;
    }
    self.bounds = CGRectIntegral(frame);

    CGAffineTransform transform = self.transform;
    transform = CGAffineTransformTranslate(transform, translation.x/2, translation.y/2);
    self.transform = transform;

    [gesture setTranslation:CGPointZero inView:view.superview];

}

这段代码在没有旋转的情况下效果很好,但是随着UIView的旋转,它会漂移。

但是,如果我在手势结束时进行整个计算,则按

if (gesture.state != UIGestureRecognizerStateEnded)
    return;

在方法的顶部,即使旋转也能正常工作,所以看起来代码可以工作,但是它可能是舍入错误吗?

这个问题好像有许多不同的形式被问到,但经过几个小时的观察,我找不到一个确切的答案。有许多StickerView示例可从中心调整大小。这个问题Resize UIView While It Is Rotated with Transform得到了一个非常完整的答案,但它并没有真正回答这个问题。

编辑:有很多回复表明三角学,我试过这个,但在我看来应该可以简单地使用CGAffineTransforms。我已经对此进行了实验,但没有取得好成绩。

2 个答案:

答案 0 :(得分:2)

我们在累积不同的转换方面也遇到了问题。只有平移或仅缩放或仅旋转才能正常工作。但是,如果我在平移后旋转,反之亦然,那么旋转将围绕父视图的0,0旋转视图,并且缩放会使图像漂移,如问题中所述。

以下两件事解决了我们的问题:

  1. 对于这些手势中的每一个,如果状态为UIGestureRecognizerStateBegan,我们将旋转视图的锚点设置为0.5,0.5。

    view.layer.anchorPoint = CGPointMake(0.5, 0.5)

  2. 当我们翻译或缩放时,我们获取视图的当前转换,将其与新的(缩放/转换)转换连接起来,如下所示: CGAffineTransformConcat(currentTransformation, newTransformation)

    但是,在旋转的情况下,我们首先将newTransformation和currentTransformation作为第二个参数连接,如下所示: CGAffineTransformConcat(newTransformation, currentTransformation)

  3. 请密切注意,我们通过转换连接的顺序非常重要,如documentation of CGAffineTransformConcat

    中所述

    另外,请阅读this以更好地了解anchorPoint,并this了解为什么它可能与您的问题有关。

答案 1 :(得分:1)

我在github上建立了一个移动,旋转和缩放的项目。它仅使用CGAffineTransforms进行旋转。此项目在视图的角落处有拖动手柄,并从对角和旋转手柄调整大小。

它使用了Erica Sadun的文章Taking Charge of UIView Transforms in iOS ProgrammingBrad Larson's / Magnus's anchor point code

链接到我的可调整大小项目:https://github.com/carolight/Resizable

相关问题