我们继续上一篇的研究:
这里直接揭晓position为什么还是 { 200 , 100 } 的悬念了。我看了很多很多篇文章都没有好好地先提醒新手们,其实这个是非常非常重要的。
position的计算是根据上面的公式用默认的anchorPoint : { 0.5, 0.5 }的值来得到的!!所以你修改anchorPoint是后来的事情,position早就根据默认的 { 0.5 , 0.5 }定好了。
所以我们接下来要研究的是如果我们同时修改position 和 anchorPoint会怎么样!?
UIView* vview = [UIView new];
[vview setFrame:CGRectMake(0, 0, 200, 100)];
[vview setBackgroundColor:[UIColor greenColor]];
vview.layer.anchorPoint = CGPointMake(0.2, 0.2);
vview.layer.position = CGPointMake(150, 80);
[self.view addSubview:vview];
NSLog(@" frame : %@", NSStringFromCGRect(vview.frame));
NSLog(@"vviewLayer's position : %@", NSStringFromCGPoint(vview.layer.position));
NSLog(@"vviewLayer's anchorPoint : %@", NSStringFromCGPoint(vview.layer.anchorPoint));
结果:
这个时候我们可以看到最终的结果position 和 anchorPoint 都是我们指定的,而Frame的Origin 就根据 上面两个和不变的bounds 移动到 { 110, 60 } 的位置。
嘻嘻,真相终于浮出水面了!!原来就是Frame Position anchorPoint 这三者的复杂巧妙的 “三角关系” 罢了!!
1. 如果不改变position 和 anchorPoint ,我们的布局就根据setFrame的传统意义来布局
2. 如果只改变了anchorPoint,系统会优先根据默认的{ 0.5, 0.5 } 来计算出Position,然后根据这个Position和anchorPoint来布局,并做适当移动,例如上篇文章
3. 如果position 和 anchorPoint都修改了,哦,对不起,前面的setFrame无效,根据后来的position和anchorPoint来重新计算Frame,并适当移动
布局公式:
Position.x = Layer.w * anchorPoint.x + Origin.x
Position.y = Layer.h * anchorPoint.y + Origin.y
UIView* vview = [UIView new];
[vview setFrame:CGRectMake(0, 0, 200, 100)];
[vview setBackgroundColor:[UIColor greenColor]];
vview.layer.anchorPoint = CGPointMake(0.2, 0.2);
vview.layer.position = CGPointMake(150, 80);
[self.view addSubview:vview];
NSLog(@" frame : %@", NSStringFromCGRect(vview.frame));
NSLog(@"vviewLayer's position : %@", NSStringFromCGPoint(vview.layer.position));
NSLog(@"vviewLayer's anchorPoint : %@", NSStringFromCGPoint(vview.layer.anchorPoint));
bounds.size 的width 和 height 都是固定值,根据anchorPoint可以算出 锚点位置,然后根据Position,移动,最后退出结果Frame,结束!