CATransform3DMakeRotation在Swift中的锚点和位置

时间:2016-10-08 21:44:10

标签: ios swift calayer catransform3d

您好我正在尝试旋转三角形CAShapeLayer。 northPole CAShapeLayer在自定义UIView类中定义。我在第一类中有两个函数来设置图层属性,另一个用于为旋转设置动画。旋转动画效果很好但在旋转完成后它会恢复到原始位置。我希望图层在旋转动画后保持给定角度(positionTo = 90.0)。

我试图在转换后设置位置以在动画后保留正确的位置。我也尝试从presentation()方法中获取位置,但这无济于事。我已经读过很多关于框架,边界,锚点的文章,但我似乎还无法理解为什么这个转换轮换不起作用。

private func setupNorthPole(shapeLayer: CAShapeLayer) {
    shapeLayer.frame = CGRect(x: self.bounds.width / 2 - triangleWidth / 2, y: self.bounds.height / 2 - triangleHeight, width: triangleWidth, height: triangleHeight)//self.bounds
    let polePath = UIBezierPath()
    polePath.move(to: CGPoint(x: 0, y: triangleHeight))
    polePath.addLine(to: CGPoint(x: triangleWidth / 2, y: 0))
    polePath.addLine(to: CGPoint(x: triangleWidth, y: triangleHeight))
    shapeLayer.path = polePath.cgPath
    shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 1.0)

动画功能:

private func animate() {
    let positionTo = CGFloat(DegreesToRadians(value: degrees))
    let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
    rotate.fromValue = 0.0
    rotate.toValue = positionTo //CGFloat(M_PI * 2.0)
    rotate.duration = 0.5
    northPole.add(rotate, forKey: nil)
    let present = northPole.presentation()!
    print("presentation position x " + "\(present.position.x)")
    print("presentation position y " + "\(present.position.y)")


    CATransaction.begin()
    northPole.transform = CATransform3DMakeRotation(positionTo, 0.0, 0.0, 1.0)
    northPole.position = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
    CATransaction.commit()
}

1 个答案:

答案 0 :(得分:0)

要解决此问题,在自定义UIView类中,我必须使用以下内容覆盖layoutSubviews():

  super.layoutSubviews()
  let northPoleTransform: CATransform3D = northPole.transform
  northPole.transform = CATransform3DIdentity
  setupNorthPole(northPole)  
  northPole.transform = northPoleTransform
相关问题