简体   繁体   中英

Get center of a UIView after CGAffineTransform

Suppose I had a small UIView as a child/subview of a larger UIView, and that child could be moved around via some CGAffineTransforms. How might the the parent know what the true 'center' of that view is within its own coordinate system? I have tried using the convertPoint routines with whatever is returned by child.center, but it isn't working... is 'center' completely bogus in this context or am I just using the wrong method?

EDIT:

After doing a bit of testing I noticed the following:

UIViews don't have an anchorPoint property, but they do have a center property. The center property is always calculated properly after applying transforms, except a translation transform, for which you have to do the following:

CGPoint realCenter = CGPointMake(myView.center.x + myView.frame.origin.x, ...);

As for CALayer s, they do have an anchorPoint property, but they lack a center property. So, what you want to do is calculate the center manually by doing calculations on the position property, anchorPoint property and the translation of your layer.

I can't provide any code, since I am not sure which method you are using, but to wrap it up, you have to roll out your own center calculator either ways.


Please look at the pictures below carefully (courtesy of Stanford iPhone Development course slides):

Before applying any rotation:

在此输入图像描述

After applying a 45° rotation:

在此输入图像描述

Conclusion:

Notice how the old center was (300, 225) and the new center is, well not new! It's the same. If you are doing everything correctly, your center should be the same. If you have another point within the view that you'd like to calculate, then you'd have to that yourself.

Please also notice how the frame changed from (200, 100, 200, 250) to (140, 65, 320, 320). This is just how UIKit does it's magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM