Vulkan
Vulkan

Reputation: 1074

How can I move and rotate a view using CGAffineTransform?

I want to move a view using a pan gesture recognizer.

UIPanGestureRecognizer *gesture;

CGPoint touch = [gesture locationInView:view.superview];

view.frame = CGRectMake(touch.x, touch.y, view.frame.size.width, view.frame.size.height);

Also, I would like to rotate the view as it moves.

view.transform = CGAffineTransformMakeRotation(multiplier * M_2_PI);

I have two basic problems:

  1. The movement didn't start from the point the user touched the view.
  2. When I try to both move and rotate the view it stretches beyond logic.

Can someone give me a very basic code sample on how to fix those issues using CGAffineTransform rather than go read this and that?

Upvotes: 0

Views: 2226

Answers (1)

Andrew Romanov
Andrew Romanov

Reputation: 5076

You can find code example here https://github.com/K-Be/ViewMovingTest Main idea is

  1. Save starting point of center of the view.
  2. Find translation and apply it for center of the view.
  3. If you want to change frame, you should set identity transform before and restore transform after applying, because frame is a function of bounds, center, transform (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instp/UIView/frame)

This is some code:

if (_panRecognizer.state == UIGestureRecognizerStateBegan)
{
    _startCenter = _frameView.center;
}
else if (_panRecognizer.state == UIGestureRecognizerStateChanged)
{
    CGPoint transition = [_panRecognizer translationInView:self.view];
    CGPoint newCenter = CGPointMake(_startCenter.x + transition.x, _startCenter.y + transition.y);
    self.frameView.center = newCenter;
}
else
{

}

and

CGAffineTransform transform = self.frameView.transform;
self.frameView.transform = CGAffineTransformIdentity;
self.frameView.frame = CGRectInset(self.view.bounds, CGRectGetWidth(self.view.bounds) / 3.0, CGRectGetHeight(self.view.bounds) / 3.0);
self.frameView.transform = transform;

Upvotes: 2

Related Questions