Search code examples
iosswiftcgaffinetransformcgpoint

update point after transform


I'm trying to change a view position using CGAffineTransform but the transform statement doesn't affect it.

For example, let's call the view that moves movingView:

At the start, movingView is at point CGPoint(x: 100, y: 100) then I'm moving movingView by this code :

movingView.transform = CGAffineTransform(translationX: 100, y: 300)

now if I do : print(movingView.layer.position), I still get

CGPoint(x: 100, y:100)

instead of

CGPoint(x: 200, y: 400)


Solution

  • Applying a transform to a view (or layer) doesn't update its center location (or position). It changes how and where the view (or layer) appear on screen but not the values of its center, (or position), or bounds properties.

    If you want to know what how the point is affected by a translation, then you can compute a new point by applying the transform to it:

    let point = CGPoint(x: 100, y: 200)
    let transform = CGAffineTransform(translationX: 20, y: 40)
    let transformedPoint = point.applying(transform) // x: 120, y: 240