Trouble translating Touch coordinates following device orientation change
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 th开发者_如何学Ce parent view passing it the last touch cordinate and return a BOOL. This works fine while the application remains in portrait orientation.
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.
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);
I read that calling the setBound method would then reset the coordinate system:
[view setBounds:view.frame];
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?
When your view is rotated (using the autorotate mechanism), iOS simply apply a CGAffineTransform
to your view, to rotate its content.
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);
The view of root viewController always acts like portrait mode. You should insert a new view inside of the root one. And this new view will acts correctly, will give right size and coordinates according to Apple says.
for example ;
UIView *v = self;
while ([[v superview] superview] != NULL) {
v = [v superview];
}
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:v];
touchPoint will be the correct one.
精彩评论