Explain the use of 'CGAffineTransform' in modifying UIViews in iOS.
Instruction: Describe how 'CGAffineTransform' can be used to scale, rotate, or translate UIViews.
Updated
Official answer
CGAffineTransform represents a two-dimensional affine transformation. Assign a transform to a UIView to scale, rotate or translate its visual presentation. Current Swift APIs include scaledBy(x:y:), rotated(by:) and translatedBy(x:y:), or corresponding initializers; angles are in radians. Reset with .identity rather than repeatedly multiplying an old transform when an absolute state is intended.
This complete geometry example demonstrates individual transforms and noncommuting composition:
import CoreGraphics
let point = CGPoint(x: 1, y: 0)
let scale = CGAffineTransform(scaleX: 2, y: 2)
let translation = CGAffineTransform(translationX: 10, y: 0)
assert(point.applying(scale) == CGPoint(x: 2, y: 0))
assert(point.applying(translation) == CGPoint(x: 11, y: 0))
let rotated = point.applying(CGAffineTransform(rotationAngle: .pi / 2))
assert(abs(rotated.x) < 1e-10 && abs(rotated.y - 1) < 1e-10)
let scaleThenTranslate = point.applying(scale.concatenating(translation))
let translateThenScale = point.applying(translation.concatenating(scale))
assert(scaleThenTranslate == CGPoint(x: 12, y: 0))
assert(translateThenScale == CGPoint(x: 22, y: 0))
For a view, transforms operate relative to its anchor point, normally the center. The example transforms a point relative to the coordinate origin; it does not claim that a view's top-left corner follows the same path. UIKit's downward-positive screen coordinates also affect the visual interpretation of rotation.
A transform changes presentation, not the Auto Layout constraints defining untransformed layout. Use bounds/center and constraints deliberately; the frame value is undefined with a nonidentity transform and should not be used as a reliable layout contract. Prefer center/constraint updates for a lasting layout-position change.
Test composition order and gesture state, avoid numerical accumulation, and respect Reduce Motion and accessibility. Scaling an image or control does not by itself supply an adaptive or accessible layout.