修改layer的anchorPoint須要注意的問題

    當咱們須要作旋轉動畫時,默認狀況都是以視圖的中點做爲軸進行旋轉的,但有時咱們須要改變旋轉的軸,這個時候須要經過改變視圖layer的anchorPoint屬性來知足需求。 測試

    anchorPoint是一個CGPoint類型,取值範圍爲(0, 0)~(1, 1),默認值爲(0.5, 0.5)。但直接改變anchorPoint會意外的發現視圖的位置改變了。看下面這個例子: 動畫

self.aView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 120))
self.aView.backgroundColor = UIColor.blackColor()
self.view.addSubview(aView)

println("view's bounds: \(self.aView.bounds)")
println("view's frame: \(self.aView.frame)")
println("view's center: \(self.aView.center)")

println("layer's bounds: \(self.aView.layer.bounds)")
println("layer's frame: \(self.aView.layer.frame)")
println("layer's position: \(self.aView.layer.position)")
println("layer's anchorPoint: \(self.aView.layer.anchorPoint)")

self.aView.layer.anchorPoint = CGPoint(x: 0, y: 0)

println()
println("view's bounds: \(self.aView.bounds)")
println("view's frame: \(self.aView.frame)")
println("view's center: \(self.aView.center)")

println("layer's bounds: \(self.aView.layer.bounds)")
println("layer's frame: \(self.aView.layer.frame)")
println("layer's position: \(self.aView.layer.position)")
println("layer's anchorPoint: \(self.aView.layer.anchorPoint)")
    這段代碼很容易理解,建立了一個UIView,是一個邊長爲120的正方形,起點爲屏幕的原點。當改變其anchorPoint時發現它在屏幕中的位置改變了。經過打印view和layer位置相關的屬性,發現view的center與layer的position、anchorPoint是關聯在一塊兒的,在屏幕中指同一個點。改變anchorPoint時,這三個值仍是指向同一個點,但layer的frame的origin將會改變。

爲了解決這個問題有兩種方法: spa

1. 定義一個私有方法傳入改變後的anchorPoint,和須要改變anchorPoint的view code

private func setAnchorPoint(anchoPoint: CGPoint, forView view: UIView) {
    var newPoint: CGPoint = CGPoint(x: view.bounds.width * anchoPoint.x, y: view.bounds.height * anchoPoint.y)
    var oldPoint: CGPoint = CGPoint(x: view.bounds.width * view.layer.anchorPoint.y, y: view.bounds.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 = anchoPoint
}
2. 直接修改該view的frame
var originRect = self.aView.frame
self.aView.layer.anchorPoint = CGPoint(x: 0, y: 0)
self.aView.frame = originRect

通過測試,兩種方式的結果是相同的。 orm

相關文章
相關標籤/搜索