1、frame和bounds的區(qū)別
UIView的布局屬性包括:frame、bouns、center,分別對(duì)應(yīng)了CALayer中frame、bounds、position。為了能清楚區(qū)分,圖層用了position,視圖用了center,但它們都代表了同樣的值。
| UIView屬性 | CALayer屬性 | 屬性說(shuō)明 |
|---|---|---|
| frame | frame | 表示相對(duì)于其父視圖的坐標(biāo)位置 |
| bounds | bounds | 表示相對(duì)于其自身的坐標(biāo)位置,{0,0}通常是其左上角 |
| center | position | 相對(duì)于父圖層錨點(diǎn)AnchorPoint所在位置 |

上圖對(duì)原有視圖做了旋轉(zhuǎn)變換,之后的frame實(shí)際上代表了覆蓋在圖層旋轉(zhuǎn)之后的整個(gè)軸對(duì)齊的矩形區(qū)域,此時(shí)frame的寬和高和bounds不再一致了。
其實(shí),對(duì)于視圖和圖層來(lái)說(shuō),frame是根據(jù)bounds、position、和transform計(jì)算而來(lái)的;所以當(dāng)其中的任何一個(gè)值發(fā)生變化時(shí),frame就會(huì)發(fā)生變化,相反改變frame也同樣影響他們當(dāng)中的值。
2、中心點(diǎn)(position)與錨點(diǎn)(anchorPoint)
position是當(dāng)前l(fā)ayer的anchorPoint在superLayer中的位置。
我們也可以更確切理解為:position是相對(duì)于superLayer來(lái)講,而anchorPoint是相對(duì)于當(dāng)前l(fā)ayer來(lái)講;只不過(guò)在默認(rèn)情況下,anchorPoint與position是重合的;錨點(diǎn)是用單位坐標(biāo)來(lái)描述的(即圖層的相對(duì)坐標(biāo)),圖層的左上角是{0,0},右下角是{1,1},因此圖層的默認(rèn)錨點(diǎn)是{0.5, 0.5},表示圖層的中間位置代表了其位置position。
下面的圖示是將錨點(diǎn)從{0.5,0.5}改為了{(lán)0,0},我們?cè)谶@里更容易看到position與anchorPoint之間的關(guān)系:

position.x = frame.origin.x + 0.5 * bounds.size.width;
position.y = frame.origin.y + 0.5 * bounds.size.height;
這里的0.5參數(shù),其實(shí)就是由于錨點(diǎn)默認(rèn)值得到的,所以改進(jìn)公式如下:
position.x = frame.origin.x + anchorPoint.x * bounds.size.width;
position.y = frame.origin.y + anchorPoint.y * bounds.size.height;
修改position與anchorPoint中任何一個(gè)屬性都不能影響另一個(gè)屬性,由此我們也可以再次改進(jìn)公式
frame.origin.x = position.x - anchorPoint.x * bounds.size.width;
frame.origin.y = position.y - anchorPoint.y * bounds.size.height;
最后得出結(jié)論:frame的origin坐標(biāo)由position與anchorPoint來(lái)共同決定;
3.錨點(diǎn)的作用
錨點(diǎn)就相當(dāng)于一個(gè)支點(diǎn),可以形象的理解為一顆固定了圖層的圖釘,尤其是我們?cè)谧鲂D(zhuǎn)動(dòng)畫(huà)時(shí),可能會(huì)需要設(shè)置此屬性來(lái)決定圖層是圍繞哪一個(gè)點(diǎn)旋轉(zhuǎn)的。