3
votes

I have a question on how I should approach rotating a UIView with touch based events.

Quite simply, I want to rotate a UIView around an anchorpoint, depending on where I touch on and off within that view. Imagine a volume knob on a hifi, which you turn with one finger.

I've built a rotation method using CAKeyframeAnimation which carries out a transform.rotation.z, however what I am not sure is if (a) I should use that in conjunction with touch methods, and (b) how I can get the coordinate/angle of the touch in relation to the underlying UIView, and subsequently turn it to point to the touch.

I hope I am making senseā€¦ Can anyone make any suggestions?

2

2 Answers

3
votes
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

CGPoint newLocationPoint = [[touches anyObject] locationInView:self.superview];

int x = self.superview.center.x;
int y = self.superview.center.y;

float dx = newLocationPoint.x - x;
float dy = newLocationPoint.y - y;

double angle = atan2(-dx,dy);

self.layer.position = self.superview.center;
self.layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);

NSLog(@"%f,%f ", dx,dy);

}

Put this in your UIView Subclass and Voila!

2
votes
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

CGPoint Location = [[touches anyObject] locationInView:self];

int x = ImageView.center.x;
int y = ImageView.center.y;

float dx = Location.x - x;
float dy = Location.y - y;

double a = atan2(-dx,dy);
ImageView.layer.position = diagramImageView.center;
ImageView.layer.transform = CATransform3DMakeRotation(a, 0, 0, 1);
}