Scale UIView with the top center as the anchor point?

前端 未结 3 1119
情话喂你
情话喂你 2020-12-23 22:43

I\'m scaling a UIView with CGAffineTransformMakeScale but I want to keep it anchored to it\'s current top center point as it\'s scaled.

I\'ve looked into setting

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 23:01

    Take a look at my answer here to understand why your view is moving when you change the anchor point: https://stackoverflow.com/a/12208587/77567

    So, start with your view's transform set to identity. When the view is untransformed, find the center of its top edge:

    CGRect frame = view.frame;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(frame), CGRectGetMinY(frame));
    

    Then the anchor point to the middle of the top edge:

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

    Now the layer's position (or the view's center) is the position of the center of the layer's top edge. If you stop here, the layer will move so that the center of its top edge is where its true center was before changing the anchor point. So change the layer's position to the center of its top edge from a moment ago:

    view.layer.position = topCenter;
    

    Now the layer stays in the same place on screen, but its anchor point is the center of its top edge, so scales and rotations will leave that point fixed.

提交回复
热议问题