Point inside a rotated CGRect

半腔热情 提交于 2020-01-01 05:36:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!