Suragch Suragch - 3 months ago 9
Swift Question

How to apply multiple transforms in Swift

I would like to apply multiple transforms to a

UIView
(or subclass of
UIView
), such as translate, rotate, and scale. I know that two transforms can be applied with
CGAffineTransformConcat
, but how do I do it if I have three or more transforms?

I have seen these questions:



but these questions are asking something different, and the given answers just talk about applying two transforms with
CGAffineTransformConcat
. Also, they use Objective-C rather than Swift.

Answer

You can apply multiple transforms by stacking them on top of each other.

var t = CGAffineTransformIdentity
t = CGAffineTransformTranslate(t, CGFloat(100), CGFloat(300))
t = CGAffineTransformRotate(t, CGFloat(M_PI_4))
t = CGAffineTransformScale(t, CGFloat(-1), CGFloat(2))
// ... add as many as you want, then apply it to to the view
imageView.transform = t

This series of transforms produces the image on the right:

enter image description here

Thanks to this answer for teaching me how to do it.

Notes

The order in which you apply the transforms matters.

The CGAffineTransforms with Make in their name create transformation matrices. You would use these if you only wanted to do a single transform or if you wanted to start a series of transforms with one of them. (In the example above we used CGAffineTransformIdentity to create our initial matrix.)

  • CGAffineTransformMakeRotation
  • CGAffineTransformMakeScale
  • CGAffineTransformMakeTranslation

The following, which we used in our example, are used to add an additional transform to an existing matrix.

  • CGAffineTransformTranslate
  • CGAffineTransformScale
  • CGAffineTransformRotate

See also