美文网首页iOS Developer
position与anchorPoint

position与anchorPoint

作者: Ozhy1991yhzO | 来源:发表于2018-07-13 15:54 被阅读11次

position与anchorPoint,傻傻分不清。
position是相对父视图而言的 是子视图anchorPoint在父视图的坐标位置。
anchorPoint 是相对于自己而言的 默认为(0.5 0.5)。

anchorPoint的定义不多说,看下图白色的点。主要讲下position与anchorPoint的关系。
anchorPoint.png
//默认
 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor redColor];
    
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [view addSubview:subView];
    subView.backgroundColor = [UIColor yellowColor];

默认情况下,黄色子视图会将红色父视图完全遮盖,这时黄色子视图的position是红色父视图的中心点为(50,50),anchorPoint 为(0.5,0.5)。

在上面的代码中加入效果是一样的。
 //position是相对父视图而言的 是子视图anchorPoint在父视图的坐标位置
    subView.layer.position = CGPointMake(50, 50);
    //anchorPoint 是相对于自己而言的 默认为(0.5 0.5)。
    subView.layer.anchorPoint = CGPointMake(0.5, 0.5);

当我们只改变anchorPoint为(0,0)时,由于position不变,会得到下图这样。由于position不变,anchorPoint为(0,0)即是子视图的左上角,position 表示anchorPoint在父视图的位置。anchorPoint与position重合。

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor redColor];
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [view addSubview:subView];
    subView.backgroundColor = [UIColor yellowColor];
    subView.layer.anchorPoint = CGPointMake(0, 0);
Simulator Screen Shot - iPhone 6 - 2018-07-13 at 14.47.20.png

那么我们改变黄色子视图的position会怎么样呢。

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 200, 100, 100)];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor redColor];
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [view addSubview:subView];
    subView.backgroundColor = [UIColor yellowColor];
    subView.layer.position = CGPointMake(100, 100);
Simulator Screen Shot - iPhone 6 - 2018-07-13 at 15.36.25.png

注意这个跟上面的例子是不同的。position改变,(100,100),position变为父视图的右下角,这时anchorPoint为(0.5,0.5),是黄色子视图的中心点,anchorPoint与position重合,就得到了如图效果。

相关文章

网友评论

    本文标题:position与anchorPoint

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