Point inside a rotated CGRect

前提是你 提交于 2019-12-03 15:41:25

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.

Use CGRectContainsPoint() to check whether a point is inside a rectangle or not.

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