在iphone中旋转叠加视图

时间:2011-02-03 14:00:13

标签: iphone objective-c cocoa-touch uikit

我有一个叠加视图(具有自绘形状),我在ImageView上显示。我希望视图可移动,可调整大小和可旋转。我可以允许用户通过从中间拖动来移动叠加层,或者通过从两侧(右侧或底部)中的一侧拖动来调整叠加层的大小。我仍然不能做的是允许用户通过移动左上边缘来旋转它。

myView.transform = CGAffineTransformMakeRotation(angle * M_PI / 180);

但是如何根据用户触摸计算角度?有什么想法吗?

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用UIRotationGestureRecognizer,它将轮值作为属性。

如果你不能使用手势识别器,请尝试这样的事情(未经测试):

// Assuming centerPoint is the center point of the object you want to rotate (the rotation axis),
// currentTouchLocation and initialTouchLocation are the coordinates of the points between 
// which you want to calculate the angle.
CGPoint centerPoint = ...
CGPoint currentTouchLocation = ...
CGPoint initialTouchLocation = ...

// Convert to polar coordinates with the centerPoint being (0,0)
CGPoint currentTouchLocationNormalized = CGPointMake(currentTouchLocation.x - centerPoint.x, currentTouchLocation.y - centerPoint.y);
CGPoint initialTouchLocationNormalized = CGPointMake(initialTouchLocation.x - centerPoint.x, initialTouchLocation.y - centerPoint.y);

CGFloat angleBetweenInitialTouchAndCenter = atan2(initialTouchLocationNormalized.y, initialTouchLocationNormalized.x);
CGFloat angleBetweenCurrentTouchAndCenter = atan2(currentTouchLocationNormalized.y, currentTouchLocationNormalized.x);

CGFloat rotationAngle = angleBetweenCurrentTouchAndCenter - angleBetweenInitialTouchAndCenter;

请参阅维基百科或进行Google搜索,以了解有关极坐标以及如何在笛卡尔坐标系和极坐标系之间进行转换的更多信息。