问题
How would you properly determine if a point is inside a rotated CGRect/frame?
The frame is rotated with Core Graphics.
So far I've found an algorithm that calculates if a point is inside a triangle, but that's not quite what I need.
The frame being rotated is a regular UIView with a few subviews.
回答1:
Let's imagine that you use transform
property to rotate a view:
self.sampleView.transform = CGAffineTransformMakeRotation(M_PI_2 / 3.0);
If you then have a gesture recognizer, for example, you can see if the user tapped in that location using locationInView
with the rotated view, and it automatically factors in the rotation for you:
- (void)handleTap:(UITapGestureRecognizer *)gesture
{
CGPoint location = [gesture locationInView:self.sampleView];
if (CGRectContainsPoint(self.sampleView.bounds, location))
NSLog(@"Yes");
else
NSLog(@"No");
}
Or you can use convertPoint
:
- (void)handleTap:(UITapGestureRecognizer *)gesture
{
CGPoint locationInMainView = [gesture locationInView:self.view];
CGPoint locationInSampleView = [self.sampleView convertPoint:locationInMainView fromView:self.view];
if (CGRectContainsPoint(self.sampleView.bounds, locationInSampleView))
NSLog(@"Yes");
else
NSLog(@"No");
}
The convertPoint
method obviously doesn't need to be used in a gesture recognizer, but rather it can be used in any context. But hopefully this illustrates the technique.
回答2:
Use CGRectContainsPoint()
to check whether a point is inside a rectangle or not.
来源:https://stackoverflow.com/questions/17002331/point-inside-a-rotated-cgrect