Search code examples
iosobjective-ccocoa-touchuiviewcatransform3d

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}}

Solution

  • 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.