指向旋转的CGRect内部(Point inside a rotated CGRect)

编程入门 行业动态 更新时间:2024-10-26 14:31:03
指向旋转的CGRect内部(Point inside a rotated CGRect)

如何正确判断一个点是否在旋转的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.

更多推荐

本文发布于:2023-08-05 14:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434745.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CGRect   Point   rotated

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!