ARKit開發(fā)中鋪天蓋地都是錨點泌辫,現(xiàn)在探究2D中錨點的表現(xiàn)巩步,于是就有了這篇文章虱饿。哩俭。绷跑。
錨點(anchorPoint)和位置(postion)的關(guān)系
position的原始定義:The layer’s position in its superlayer’s coordinate space。
中文可以理解成為position是layer相對superLayer坐標(biāo)空間的位置凡资。所以請記住這個結(jié)論:position的位置是根據(jù)anchorPoint來確定的砸捏。
即:anchorPoint決定position
anchorPoint、position隙赁、frame之間的關(guān)系
anchorPoint的默認(rèn)值為 (0.5,0.5)垦藏,也就是anchorPoint默認(rèn)在layer的中心點。計算 position的值便可以用下面的公式計算:
position.x = frame.origin.x + 0.5 * bounds.size.width伞访;
position.y = frame.origin.y + 0.5 * bounds.size.height掂骏;
里面的0.5是因為anchorPoint取默認(rèn)值,更通用的公式應(yīng)該是:
position.x = frame.origin.x + anchorPoint.x * bounds.size.width厚掷;
position.y = frame.origin.y + anchorPoint.y * bounds.size.height弟灼;
如果單方面修改layer的position位置级解,會對anchorPoint有什么影響呢?修改anchorPoint又如何影響position呢田绑?
根據(jù)代碼測試勤哗,兩者互不影響,受影響的只會是frame.origin掩驱。
所以我們又可以得出今天的第二個結(jié)論: anchorPoint和position互不影響芒划,故受影響的只有frame。
現(xiàn)在又可以得出一個換湯不換藥的裝逼公式:
frame.origin.x = position.x - anchorPoint.x * bounds.size.width昙篙;
frame.origin.y = position.y - anchorPoint.y * bounds.size.height腊状;
PS:這就解釋了為什么修改anchorPoint會移動layer,因為position不受影響苔可,只能是frame.origin做相應(yīng)的改變缴挖,因而會移動layer。
優(yōu)化
在實際情況中焚辅,可能還有這樣一種需求映屋,我需要修改anchorPoint而不想移動layer,在修改anchorPoint后再重新設(shè)置一遍frame就可以達到目的同蜻,這時position就會自動進行相應(yīng)的改變棚点。
代碼:
- (void) setAnchorPoint:(CGPoint)anchorpoint forView:(UIView *)view{
CGRect oldFrame = view.frame;
view.layer.anchorPoint = anchorpoint;
view.frame = oldFrame;
}
總結(jié)
1、position是layer中的anchorPoint在superLayer中的位置坐標(biāo)湾蔓。
2瘫析、互不影響原則:單獨修改position與anchorPoint中任何一個屬性都不影響另一個屬性。
3默责、frame贬循、position與anchorPoint有以下關(guān)系:
frame.origin.x = position.x - anchorPoint.x * bounds.size.width;
frame.origin.y = position.y - anchorPoint.y * bounds.size.height桃序;