如何正确地确定一个点是否在旋转的CGRect/frame内?
使用Core Graphics旋转框架。
到目前为止,我已经找到了一个算法来计算一个点是否在三角形内,但这还不是我需要的。
被旋转的框架是一个带有几个子视图的常规UIView
假设您使用transform
属性来旋转视图:
self.sampleView.transform = CGAffineTransformMakeRotation(M_PI_2 / 3.0);
如果你有一个手势识别器,例如,你可以看到如果用户在那个位置点击locationInView
与旋转视图,它会自动为你考虑旋转:
- (void)handleTap:(UITapGestureRecognizer *)gesture
{
CGPoint location = [gesture locationInView:self.sampleView];
if (CGRectContainsPoint(self.sampleView.bounds, location))
NSLog(@"Yes");
else
NSLog(@"No");
}
或者您可以使用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");
}
convertPoint
方法显然不需要在手势识别器中使用,但它可以在任何上下文中使用。希望这能说明这个技巧。
使用CGRectContainsPoint()
检查点是否在矩形内