简体   繁体   中英

Rotate UIView using UITouch

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?

- (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!

- (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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM