为了旋转图像视图,我应用了一个变换旋转,这工作得很好。它看起来像这样:
CGAffineTransform trans = self.transform;
self.transform = CGAffineTransformRotate(trans, delta);
问题出现在用户尝试通过触摸移动元素时。在touchesBegan:WithEvent:方法中,我将起始点保存在类变量startLocation中:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
}
在touchesMoved:withEvent:方法中,我有以下代码。如果图像视图上没有旋转变换,这段代码可以正常工作:
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView:self];
CGFloat dx = pt.x - startLocation.x;
CGFloat dy = pt.y - startLocation.y;
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
self.center = newCenter;
}
但如果图像视图上有旋转变换,那么每次touchesMoved事件中,图像视图就会在屏幕上翻滚并很快消失。在调试器中,我观察到pt的值变得极大。我意识到需要对该点进行变换,于是我这样做:
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView:self];
if (!CGAffineTransformIsIdentity(self.transform)) {
pt = CGPointApplyAffineTransform(pt, self.transform);
}
CGFloat dx = pt.x - startLocation.x;
CGFloat dy = pt.y - startLocation.y;
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
}
这个方法效果好多了。现在我可以拖动图片在屏幕上移动。但是第一次移动会导致图片在一个方向上或另一个方向上突然抖动,这取决于转换中的旋转角度和图像视图的尺寸。
如何在没有初始抖动的情况下移动图像视图?
为什么我不需要转换startLocation(即我捕捉到的触摸开始时的点)?