Search code examples
iosobjective-ccgaffinetransform

Objective-C Transform to X and Y


I have been researching CGAffineTransforms and was wondering if there was a way to take your view and zoom in on an x,y coordinate. I have the scaling portion down with the function:

       CGAffineTransformMakeScale(4.00 ,4.00);

However I am uncertain how to tie the scaling with a possible x,y coordinate. Has anyone ever done something like this? Am I incorrect in the use of these function possibly?

       -(void)buttonSelected:(id)sender
       {
          UIButton *b = sender;
          CGPoint location = b.frame.origin;

          [UIView animateWithDuration:1.3f delay:0.0f options:UIViewAnimationCurveEaseIn animations:^{
               CGAffineTransform totalTransform =
               CGAffineTransformMakeTranslation(-location.x  , -location.y );
               totalTransform = CGAffineTransformScale(totalTransform, 4.0f, 4.0f);
               totalTransform = CGAffineTransformTranslate(totalTransform, location.x , location.y );
               [self.view setTransform:totalTransform];
           }completion:^(BOOL finished) {
           }];

       }

Solution

  • You would either construct a transform that performed the three steps:

    • move point you want to scale around to the centre of the layer;
    • scale;
    • move the object back so that the original centre is back in the centre.

    So, e.g.

    // to use a point that is (109, 63) from the centre as the point to scale around
    CGAffineTransform totalTransform =
                      CGAffineTransformMakeTranslation(-109.0f, -63.0f);
    totalTransform = CGAffineTransformScale(totalTransform, 4.0f, 4.0f);
    totalTransform = CGAffineTransformTranslate(totalTransform, 109.0f, 63.0f);
    

    Or, arguably more simply adjust the view.layer's anchorPoint. The gotcha with the second idea is that when you first adjust the anchor point you'll get an immediate transform because all other positioning is in terms of the centre.