如何正确判断一个点是否在旋转的CGRect /框架内?
使用Core Graphics旋转框架。
到目前为止,我已经找到了一个算法来计算点是否在三角形内,但这并不是我所需要的。
正在旋转的框架是一个具有几个子视图的常规UIView。
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.
最满意答案
假设您使用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方法显然不需要在手势识别器中使用,而是可以在任何情况下使用。 但希望这可以说明这种技术。
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.
更多推荐
发布评论