美文网首页
IOS 对anchorPoint与position的理解

IOS 对anchorPoint与position的理解

作者: Johnny_Wu | 来源:发表于2018-06-04 18:39 被阅读0次

anchorPoint与position

position:控制本层在其父层的位置

anchorPoint:本层自身的定位点,与position重合。控制自身的tranform变换的起始点(默认为(0.5,0.5)),(0,0)为自身左上角,比如说图形旋转,那么就是绕着这个点旋转的。

简单说:position表示在父层的位置,但它只是一个点,层是有大小的,还得在本层找到一个自身点anchorPoint,与position对应,这样才能确定层的位置。父层要子层自己定出一个点,与父层的position对应上。position与anchorPoint永远是重合的。

改变position或anchorPoint都会使子层的frame发生改变。具体怎么变化,你只需这样想就可以了:anchorPoint点必须要向position点移动,直到重合。不须要背!

简单例子:

//anchorPoint与position

- (void)testAnchorPoint

{

    CAShapeLayer *grad3 = [CAShapeLayer layer];

    grad3.frame = CGRectMake(20, 260, 10, 100);

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:grad3.bounds];

    grad3.path = path.CGPath;

    //加入动画

    CABasicAnimation *animation;

    animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];

    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

    animation.duration = 0.5;

    animation.delegate= nil;

    animation.fromValue = [NSNumber numberWithFloat:0.1];

    animation.toValue = [NSNumber numberWithFloat:1];

    [grad3addAnimation:animation forKey:@"transform.scale.y"];

    [self.view.layer addSublayer:grad3];

    //多加一个对比的点

    UIView *pointView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

    pointView.center = CGPointMake(40, 260);

    pointView.layer.cornerRadius = 5;

    pointView.backgroundColor = [UIColor redColor];

    [self.view addSubview:pointView];

}

运行如下:

动画是由图形中间点往两端延伸,这是我之前做柱状图遇到的问题。现在得实现以下改变:

1、得让动画从图形底部向上延伸,就是从底部往上升长的动作

上面我们说过,anchorPoint是图层动画的起始点,那么通过改变anchorPoint就可以控制动画开始的位置。这里,我们把anchorPoint点由默认的(0.5,0.5)改为底部的(0.5,1)

[grad3 setAnchorPoint:CGPointMake(0.5, 1)];

结果如下:

实现了动画由底部向上延伸,但图层的位置也发生了改变。为什么图层位置会发送改变,因为上面说的:anchorPoint点必须要向position点移动,直到重合。Position点在图层中间(这是相对父层的位置),anchorPoint在图层底部,所以,图层会往上移动,直到anchorPoint与Position重合。

2、把图层底部与红点中心的Y对齐,就是把柱状图控制在我的封装的View中。

我们可以通过调整Position来调整图层的位置。

[grad3setPosition:CGPointMake(grad3.position.x, 260)];

红点中心的位置的Y为:260

结果如下:

anchorPoint会向Position重合,所以在上一结果的下,图层还会往上移动1/2的高度便可以让anchorPoint与Position重合。得到上面的结果。

相关文章

网友评论

      本文标题:IOS 对anchorPoint与position的理解

      本文链接:https://www.haomeiwen.com/subject/hppysftx.html