Search code examples
iphoneobjective-cioscgaffinetransform

How to restore saved transform when flipped



I persist a transform and a frame of an object. When the app reloads I simply need to restore the frame and the transform on a new view. You would think that you could simply set the frame and transform to the saved values, but you can't. Doing so creates undesired results.

http://iphonedevelopment.blogspot.com/2008/10/demystifying-cgaffinetransform.html

Says : "When you apply success transformations, the order matter. Rotating and then translating will give you a different result then translating and then rotating. This can bite you if you're not careful."

I only have transform problems when I save an transform that has been FLIPPED & ROTATED. My save values are identical to the values that are applied to the restored view.

Actual Results:

When doing :

myNewView.frame = savedFrame

myNewView.transform = savedTransform

My view will shift down and to the right (out of place).

Can someone help me restore my transform in the proper order of operations?

Again, I have confirmed that my saved and loaded transform data is perfect, so I know its an order of operations problem, im just not smart enough to figure out what to do next :P


Solution

  • To undo the saved transformation, you need the inverse transformation. See the heading Stepping Back in the page you referenced. Try:

    myNewView.transform = CGAffineTransformInvert(savedTransform);
    

    An arbitrary matrix is not always invertible, but you are usually safe with an affine transformation. Here are some special cases to watch out for.

    In general, matrix inversion may lead to round-off errors, so if you need to do this repeatedly, you may need to use a different approach.

    EDIT:

    Having re-read the question, I suspect that the origin of the transformation may have changed. When a rotation is involved, rotating about a different origin will appear to as an unexpected translation. From the docs, the origin is either the view's center, or the layer's anchor point. I suggest checking these properties when you save the transform and see if they differ when you restore.