3 回答
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
Core Animation Programming Guide 的Layer Geometry and Transforms部分解釋了CALayer的position和anchorPoint屬性之間的關(guān)系。基本上,層的位置是根據(jù)圖層的anchorPoint的位置指定的。默認(rèn)情況下,圖層的anchorPoint為(0.5,0.5),位于圖層的中心。設(shè)置圖層的位置時(shí),您將在其超層圖層的坐標(biāo)系中設(shè)置圖層中心的位置。
因?yàn)槲恢檬窍鄬?duì)于圖層的anchorPoint,所以在保持相同位置的同時(shí)更改該anchorPoint會(huì)移動(dòng)圖層。為了防止這種移動(dòng),您需要調(diào)整圖層的位置以考慮新的anchorPoint。我這樣做的一種方法是抓取圖層的邊界,將邊界的寬度和高度乘以舊的和新的anchorPoint的標(biāo)準(zhǔn)化值,取兩個(gè)anchorPoints的差值,并將該差值應(yīng)用于圖層的位置。
您甚至可以通過使用CGPointApplyAffineTransform()UIView的CGAffineTransform以這種方式考慮輪換。
TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
我有同樣的問題。Brad Larson的解決方案即使在視圖旋轉(zhuǎn)時(shí)也能很好地工作。這是他的解決方案翻譯成代碼。
-(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view
{
CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x,
view.bounds.size.height * anchorPoint.y);
CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x,
view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
CGPoint position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = anchorPoint;
}
而快速的等價(jià)物:
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = CGPointApplyAffineTransform(newPoint, view.transform)
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
SWIFT 4.x
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x,
y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x,
y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
- 3 回答
- 0 關(guān)注
- 833 瀏覽
添加回答
舉報(bào)
