CALayer中的锚点

Cry*_*tal 2 iphone uiview uigesturerecognizer

查看Apple文档中的Touches示例,有以下方法:

// scale and rotation transforms are applied relative to the layer's anchor point
// this method moves a gesture recognizer's view's anchor point between the user's fingers
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        UIView *piece = gestureRecognizer.view;
        CGPoint locationInView = [gestureRecognizer locationInView:piece];
        CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];

        piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
        piece.center = locationInSuperview;
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个问题,有人可以解释在子视图中设置锚点的逻辑,并改变超视图的中心(就像为什么这样做)?

最后,数学如何为anchorPoint语句工作?如果你的视图边界为500,500,并且说你用100,100用一根手指触摸,500,500用另一根触摸.在此框中,您的常规锚点为(250,250).现在是???? (没有线索)

谢谢!

Dee*_*olu 9

center视图的属性是仅仅反映position其衬里层的属性.令人惊讶的是,这意味着center不需要在你的中心view.其中position位于其范围内是基于anchorPoint这需要在任何地方的值(0,0)之间和(1,1).可以把它看作是否position在其范围内的谎言的标准化指标.如果你要改变无论是anchorPointposition,边界将调整本身,而不是位置漂移WRT其superlayer/ superview.所以要重新调整,position以便视图的框架不会移动,可以操纵center.

piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
Run Code Online (Sandbox Code Playgroud)

想象一下原始的东西在哪里O是接触点,

+++++++++++  
+ O       +         +++++++++++
+    X    +  -->    + X       +
+         +         +         +
+++++++++++         +         +
                    +++++++++++
Run Code Online (Sandbox Code Playgroud)

现在我们希望它X处于用户触摸的位置.我们这样做是因为所有缩放和旋转都是基于position/ 完成的anchorPoint.要将框架调整回原始位置,我们将"center"视图设置为触摸位置.

piece.center = locationInSuperview;
Run Code Online (Sandbox Code Playgroud)

所以这反映在视图中重新调整其框架,

                    +++++++++++  
+++++++++++         + X       +
+ X       +  -->    +         +
+         +         +         +
+         +         +++++++++++
+++++++++++
Run Code Online (Sandbox Code Playgroud)

现在,当用户旋转或缩放时,就会发生轴,就好像轴位于触摸点而不是视图的真实中心.

在你的例子中,视图的位置可能最终是平均值,即(300,300),这意味着anchorPoint将是(0.6,0.6)并且作为响应,frame将向上移动.为了重新调整我们将中心移动到触摸位置将frame向后移动.

  • @Crystal有没有帮忙? (2认同)