设备方向更改后无法转换触摸坐标 [英] Trouble translating Touch coordinates following device orientation change

查看:52
本文介绍了设备方向更改后无法转换触摸坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个自定义类,它创建一个包含图像的视图并处理它自己的所有触摸事件.有时我想检查移动它是否会导致它与父视图上的另一个视图重叠.因此,在相关触摸事件之后,我调用父视图上的一个方法,将最后一个触摸坐标传递给它并返回一个 BOOL.当应用程序保持纵向时,这可以正常工作.

Ok the scenario is that I have a custom class which creates a view containing an image and handles all its own touch events. Occasionally I want to check if moving it would cause it to overlap another view on a parent view. So after the relevent touch event I call a method on the parent view passing it the last touch cordinate and return a BOOL. This works fine while the application remains in portrait orientation.

问题是在旋转设备之后,所有图像都自动旋转了,与父视图相比,传递的 CGPoint 现在处于旋转坐标系中,并且调用的 CGRectContainsPoint 方法不再正常工作.

Problem is after rotating the device and all the images are auto-rotated for me the CGPoint being passed is now in a rotated coordinate system compared with the parent view and the CGRectContainsPoint method being called no longer works properly.

在我的 willAnimateRotationToInterfaceOrientation 方法中,我正在调整每个自定义视图的位置以改进新方向的布局,例如

In my willAnimateRotationToInterfaceOrientation method I am adjusting the position of each custom view to improve the layout for the new orientation e.g.

view.frame = CGRectMake((view.frame.origin.x*1.5),(view.frame.origin.y/1.5),view.frame.size.width,view.frame.size.height);

我读到调用 setBound 方法会重置坐标系:

I read that calling the setBound method would then reset the coordinate system:

[view setBounds:view.frame];

但这对我的情况没有影响.我也尝试修改 'convertPoint:toView' 但它给出的值也没有多大意义.我的结论是在坐标系旋转的情况下它不起作用?

but this isn't making a difference in my case. I also tried tinkering with 'convertPoint:toView' but the values it was giving weren't making much sense either. I concluded it wouldn't work in the case where the coordinate system had been rotated?

推荐答案

当您的视图旋转(使用自动旋转机制)时,iOS 只需将 CGAffineTransform 应用于您的视图,以旋转其内容.

When your view is rotated (using the autorotate mechanism), iOS simply apply a CGAffineTransform to your view, to rotate its content.

因此,您应该能够检索当前应用于 UIView 的 CGAffineTransform,然后使用 CGPointApplyAffineTransform 将此 CGAffineTransform 应用于 UITouch 的点(可能在反转 AffineTransform 之后,将逆变换应用于你的意思.没有测试这段代码,只是凭记忆写的)

So you should be able to retrieve the current CGAffineTransform applied to your UIView, then apply this CGAffineTransform to the point of your UITouch using CGPointApplyAffineTransform (probably after inverting the AffineTransform, to apply the inverse transformation to your point. Haven't tested this code, only writing this from memory)

UITouch* touch = [touches anyObject];
CGPoint pt = [touch locationInView:self];
CGAffineTransform inverseTransform = CGAffineTransformInvert(self.transform);
CGPoint transformedPoint = CGPointApplyAffineTransform(pt,inverseTransform);

这篇关于设备方向更改后无法转换触摸坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆