Decomposing CGAffineTransform in rotate, scale, and translate components

Viewed 163

I am trying to break CGAffineTransform into rotate, scale, and translate components as follows:

public extension CGAffineTransform {
  func rotationRadians() -> CGFloat {
      return atan2(b, a)
  }

   func translation() -> CGPoint {
      return CGPoint(x: tx, y: ty)
   }

   func scaleXY() -> CGPoint {
      let scalex = sqrt(a * a + c * c)
      let scaley = sqrt(d * d + b * b)
      return CGPoint(x: scalex, y: scaley)
    }
}

Now I try this code on random transform by breaking it and then constructing it back from the same components, but the answer never comes out to be same, no matter what order I use in concatenation. Not sure what I am doing wrong.

   let randomTransform = __CGAffineTransformMake(2.078, 3.459, 1.676, 0, 591, 397)
   let rotationRadians = randomTransform.rotationRadians()
   let scaleXY = randomTransform.scaleXY()
   let translation = randomTransform.translation()
                
   let translationTransform = CGAffineTransform(translationX: translation.x, y: translation.y)
   let scalingTransform = CGAffineTransform(scaleX: scaleXY.x, y: scaleXY.y)
   let rotationTransform = CGAffineTransform(rotationAngle: rotationRadians)
                
   var newTransform =  rotationTransform.concatenating(scalingTransform).concatenating(translationTransform)
                
   NSLog("New transform \(newTransform), original \(randomTransform)")
             

Here is the output from console:

New transform CGAffineTransform(a: 1.374790977280978, b: 2.965084308709465, c: -2.2884513909600113, d: 1.7812793274062642, tx: 591.0, ty: 397.0), original CGAffineTransform(a: 2.078, b: 3.459, c: 1.676, d: 0.0, tx: 591.0, ty: 397.0)
1 Answers
Related