动画效果工作生活

iOS开发 position 和 锚点anchorPoint

2019-07-02  本文已影响0人  霸_霸霸

之前也看了锚点和position的关系,没几天又忘了,做个记录吧!

1.position

定义:某一个视图的layer的position表示,该视图的layer的锚点父视图的layer中的位置,默认的数值是视图layer的中点的数值。

从上面的定义的第二句来看,position表示的是在父视图中的位置!

2. anchorPoint

定义:锚点,就像船锚一样,起着固定的作用,有风浪时,船会围着船锚旋转;锚点也是这样的,说白了就是固定视图用的点,每当我们给视图添加一个旋转动画时,就是围绕该点进行旋转的。

3. 记住一点:position 和 锚点 必须是重合的!

4. 例子

    UIView *testView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    testView.backgroundColor = [UIColor redColor];
    [self.view addSubview:testView];
    
    UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 60)];
    blueView.backgroundColor = [UIColor blueColor];
    [testView addSubview:blueView];

看下初始的样子


初始视图.png

此时position的值是蓝色视图的中心点坐标(50, 30),锚点是默认的(0.5, 0.5)

1. 修改蓝色矩形的锚点anchorPoint 为(0, 0),position不变(50, 30)

    blueView.layer.anchorPoint = CGPointMake(0, 0);

结果:


修改锚点.png

我们发现,锚点和position依然是重合的,但是蓝色视图的位置却发生了变化;
原因:position还是(50, 30),但是锚点从蓝色视图的中心点变成了左上角的点,由于position和锚点必须是重合的(即position是锚点在父视图layer中的位置),所以蓝色视图的位置发生了改变。

如何变回去呢? ---- 修改position为(0, 0)

blueView.layer.position = CGPointMake(0, 0);
同时修改锚点和position.png

2. 让图中的蓝色矩形旋转

    UIView *testView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    testView.backgroundColor = [UIColor redColor];
    [self.view addSubview:testView];
    
    UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 60)];
    blueView.backgroundColor = [UIColor blueColor];
    [testView addSubview:blueView];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    animation.duration = 1;
    animation.toValue = @(2 * M_PI);
    animation.repeatCount = 100;
    [blueView.layer addAnimation:animation forKey:@"rotation"];

效果:


修改锚点之前.gif

修改blueView的锚点为(0, 0)

blueView.layer.anchorPoint = CGPointMake(0, 0);

结果:


修改锚点之后.gif

分析
比较之前的动画,发生了2个改变:

  1. blueView的位置发生了变化
  2. blueView旋转的中心发生了变化

位置的变化,我们在上面已经分析过了,我们这里还是说一说锚点的“固定视图功能”;我们可以看到,随着锚点的变化,视图旋转的中心也发生变化,就像船锚一样,船(视图)总是围着船锚(锚点)旋转的。

上一篇 下一篇

猜你喜欢

热点阅读