Search code examples
iosswiftcgaffinetransform

Get frame of subview inside a view that's being rotated (CGAffineTransform)


I have a similar problem whose solution has been proposed here: https://stackoverflow.com/a/16511494/3134192

I have a outer view containing an inner view. The outer view is rotating (ongoing, endless animation) using CGAffineTransform. I want to calculate the frame of the inner view relative to the rotated outer view (-> the frame of the actual displayed inner view, as it's rotating with the outer view).

I'm not quite understanding these convert() methods of UIKit. I never get which coordinate systems it's converted from and to. Also, the solution from the question is not working for me, it's giving me an incorrect frame.

I'd appreciate any help with this. Thanks!


Solution

  • So it sounds like you have a situation like this:

    enter image description here

    The frame of innerView "relative to the outer view" is unchanged, by definition, since its frame is specified in the coordinate space of its superview. So maybe you're looking for its frame relative to the enclosing rootView. That's an interesting question, since it's no longer axis-aligned and thus "undefined" in some sense. (See the docs for the frame property of UIView regarding non-identity transform.)

    I'm not actually sure what you'd get back if you ran innerView.convert (innerView.frame, to: rootView) on this non-axis-aligned rect. Perhaps something like this:

    enter image description here

    However, you could easily ask for, say, the top-left corner or the center of innerView relative to rootView like so: innerView.convert (innerView.frame.origin, to: rootView).