Get size of UIView after applying CGAffineTransform

Marin Todorov picture Marin Todorov · Apr 22, 2010 · Viewed 14.9k times · Source

I was surprised not to find an answer to this question, maybe is something very simple I somehow overlook :

How to get the real size of an UIView after I apply a CGAffineTransform to it?

eg.

my UIView has size 300 x 200, I apply a scaling transform let's say factor 2 both horizontal and vertical, so the UIView now takes 600 x 400 on the screen, but it's bounds and it's layer's bounds are still returning a size of 300 x 200 ... where do I find the real size of the UIView ?

ps. forgot to mention I want to also rotate the uiview. If I apply only scaling CGSizeApplyAffineTransform works great, but when there's also rotation, then it does not work properly.

Edit: drawnonward pointed me in the right direction, I just refined a bit the code to compile and here it is :

UIView* view = (your view being transformed);
CGAffineTransform trans = (view.transform or create a new transformation);

CGRect rect = [view bounds];
CGMutablePathRef path = CGPathCreateMutable();
rect.origin = CGPointZero;
CGPathAddRect(path , &trans , rect);
rect = CGPathGetBoundingBox( path );
CGPathRelease( path );

Now rect.size contains the dimensions of the view with the transformation applied Thanks again to drawnonward

Answer

Nikso picture Nikso · Jul 6, 2011

I use this in Objective C:

CGRect transformedBounds = CGRectApplyAffineTransform(view.bounds, view.transform);

or in Swift 4:

let transformedBounds = view.bounds.applying(view.transform)