Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of CGAffineTransformMakeScale with CGREct and with UIView

I have a view with a frame defined as (0,0,320,480).
I call transformation on this view:

self.myView.transform = CGAffineTransformMakeScale(factor, factor); 

The view will scale preserving a central position on the screen and his frame after my changes will be for example (34,-8,251,376), as you can see X and Y are now different from 0.

If i use the same function on a CGRect with frame (0,0,320,480):

CGAffineTransform t = CGAffineTransformMakeScale(factor,factor);
CGRect rect2 = CGRectApplyAffineTransform(rect,t);

rect2 will preserve 0 for X and Y and i'll obtain as result something like (0,0,251,376)

Why X and Y for rect2 doesn't change as in UIView example ?

like image 633
MatterGoal Avatar asked Feb 25 '23 19:02

MatterGoal


2 Answers

It's true that you're not technically supposed to look at the frame property of a UIView after transformation, but it's also not technically pertinent to the question you're asking.

When applying CAffineTransforms to a UIView, the transformation takes into consideration the UIView's backing CALayer's anchorPoint property. From the CALayer docs on anchorPoint:

Defaults to (0.5, 0.5), the center of the bounds rectangle.

This means that when you apply that scale transform, it uses the center of the view as the anchor point, so the view scales around that location. I'm guessing if you were to set the anchor point to (0, 0), it would behave like CGRect does.

CGRect, on the other hand, is a simple C struct, and doesn't have a backing layer or an anchor point. Thus the difference in behavior.

like image 200
Matt Wilding Avatar answered May 04 '23 00:05

Matt Wilding


The UIView reference page says specifically:

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

So don't look at a view's frame after setting it's transform.

like image 35
Caleb Avatar answered May 04 '23 00:05

Caleb