Set center point of UIView after CGAffineTransformMakeRotation

Dave picture Dave · Dec 25, 2010 · Viewed 7.2k times · Source

I have a UIView that I want the user to be able to drag around the screen.

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{
    CGPoint pt = [[touches anyObject] locationInView:self];

    CGPoint center = self.center;

    CGFloat adjustmentX = pt.x - startLocation.x;
    CGFloat adjustmentY = pt.y - startLocation.y;

   center.x += adjustmentX;
   center.y += adjustmentY;

   [self setCenter:center];
}

works perfectly until I apply a transform to the view as follows:

self.transform = CGAffineTransformMakeRotation(....);

However, once the transform has been applied, dragging the UIView results in the view being moved in a exponential spiral effect.

I'm assuming I have to make an correction for the rotation in the touchesMoved method, but so far all attempts have eluded me.

Answer

tsakoyan picture tsakoyan · Dec 25, 2010

You need to translate your transform to your new coordinates because a transform other than the identity is assigned to your view and moving its center alters the transform's results.

Try this instead of altering your view's center

self.transform = CGAffineTransformTranslate(self.transform, adjustmentX, adjustmentY);