Colas
Colas

Reputation: 3573

How to compute the frame of a UIView before the transform?

Question

I have a UIView and I apply to it a CGAffineTransform. I would like to be able to know the frame of the view if the transform had not be applied.

I am looking for a (simple) solution that handles the case where the transform is the "zero-transform" (which is not invertible).

My attempt

The following does not work for the "zero-transform", I guess.

CGRect result ;

CGAffineTransform transform = self.transform ;

result = CGRectApplyAffineTransform(self.frame, CGAffineTransformInvert(transform)) ;

return result ;

Why?

I need to do this for an animation:

Remarks

My transform is a scale transform.

Upvotes: 5

Views: 3702

Answers (2)

Leslie Godwin
Leslie Godwin

Reputation: 2658

Swift 4.1 version:

extension UIView
{
    var frameWithoutTransform: CGRect
    {
        let center = self.center
        let size   = self.bounds.size

        return CGRect(x: center.x - size.width  / 2, 
                      y: center.y - size.height / 2,
                  width: size.width,
                 height: size.height)
    }
}

Upvotes: 0

rintaro
rintaro

Reputation: 51911

transform does not affect center nor bounds.

So, you can calculate it by this simple code:

    CGPoint center = view.center;
    CGSize size = view.bounds.size;

    CGRect frameForTransformIdentity = CGRectMake(
        center.x - size.width / 2,
        center.y - size.height / 2,
        size.width,
        size.height
    );

Upvotes: 17

Related Questions