'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.
Solution 1:[1]
In Swift 3, these have been replaced by functions on CGAffineTransform itself, which can be chained.
extension CGAffineTransform {
public func translatedBy(x tx: CGFloat, y ty: CGFloat) -> CGAffineTransform
public func scaledBy(x sx: CGFloat, y sy: CGFloat) -> CGAffineTransform
public func rotated(by angle: CGFloat) -> CGAffineTransform
}
so for example
let transform = CGAffineTransform(scaleX: 1.0, y: 3.0).translatedBy(x: 12, y: 9).rotated(by: 17.0)
Solution 2:[2]
the trick is that
view.transform.translatedBy(x: 100, y: 100) is NOT changing view.transform. it just returns the new CGAffineTransform that you need to ASIGN back to view.transform.
view.transform = view.transform.translatedBy(x: 100, y: 100)
You can do that as many times as you need or in a sequence
view.transform = view.transform.translatedBy(x: 100, y: 100).rotated(by: CGFloat.pi / 2).scaledBy(x: 2, y: 2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | giacoder |
