Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do layer transforms affect a UIView's frame?

Transforming a UIView affects its frame. Transforming a UIView's layer also affects the views frame in the same way. So scaling a view's layer, scales the frame. I'm trying to understand why transforms to the layer affect the views frame (even when view.layer.masksToBounds = NO is set).

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
NSLog(@"Before: %@", NSStringFromCGRect(view.frame));
// Output: {{0, 0}, {50, 50}}

// View transform applied
view.transform = CGAffineTransformMakeScale(2, 2);
NSLog(@"%@", NSStringFromCGRect(view.frame));
// Output: {{-25, -25}, {100, 100}}


// Layer transform applied
view.transform = CGAffineTransformIdentity;
view.layer.transform = CATransform3DMakeScale(2, 2, 1);
NSLog(@"%@", NSStringFromCGRect(view.frame));
// Output: {{-25, -25}, {100, 100}}
like image 610
Warpling Avatar asked Apr 09 '15 02:04

Warpling


3 Answers

You shouldn't look at the frame value once you have a transform, since it's undefined what it contains at that point. This is mentioned in the documentation for the frame property on UIView:

WARNING

If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.

If you need that to modify the frame, you have to do so using the center and bounds properties instead.

like image 97
David Rönnqvist Avatar answered Nov 15 '22 18:11

David Rönnqvist


A frame is a very specific thing.

This rectangle defines the size and position of the view in its superview’s coordinate system. You use this rectangle during layout operations to size and position the view.

Transforms applied to a view effect the origin and size of that view in the superview which is why the view's frame changes.

Transforming subviews will effect the frames of the subviews, but not their superview's frame.


It's worth noting that bounds differs from frame in this respect. The bounds of a view is the origin and size of a view within it's own coordinate system. Transforms should not change a view's bounds, because the transform changes the size and placement of the view for external coordinates, but not the view's internal coordinates.

like image 23
Jeffery Thomas Avatar answered Nov 15 '22 19:11

Jeffery Thomas


The frame is a computing property. Basically, it's synthesized from center and bounds.( To know more, please search for anchorPoint of CALayer). What's more, when transform is taken into consideration. The frame will be a bounding box that will cover the original box, even rotation or scale is applied. And the default implementation of hitTest and pointInside will use the final frame, which means you can touch the translated or rotated view normally.

like image 1
user3349433 Avatar answered Nov 15 '22 18:11

user3349433