如何在旋转的UIView中使用CGRectContainsPoint()

我有一个UIView ,用户可以点击UIView “select”或突出显示它所代表的应用程序内的“事物”。 我使用CGRectContainsPoint(thing.frame,tapPoint)来实现这一点,其中thing.frameUIView的框架,而tapPointtapPoint中的轻敲点。 这工作完美。

..通过设置transform属性(具有CGAffineTransform值)旋转UIView时。 当UIView像这样旋转时,该frame变成封装旋转视图的扁平正方形。

下面是这个问题的例子(框架属性被标记为A,而可视化的UIView框架被标记为B):

不旋转时

 +------------------+ | A == B | +------------------+ 

旋转时

 +-----------------+ | A . | | . . | | . . | | . . | | . B . | | . . | | . . | | . | +-----------------+ 

我想要捕获位于rect BUIView的真实边界,旋转的)范围内的水龙头,但不是当它们仅在rect AUIViewframe属性的值)内而不是B

我怎样才能计算给定的点是否在旋转的UIView的真正的边界/框架/边界内? 有没有一个方便的方法呢? 或者我需要使用我自己的几何来计算B的坐标和尺寸?

(如果是后者,请包括一个build议,这样我们可以尽可能地完成答案,谢谢!)

你们正在发现每个人首先为框架而工作的基本绊脚石。

框架是视图适合的最小可能(非旋转)的矩形,考虑到转换。 意思是,如果要testing触摸,只要在最小的可能矩形内,就可以login视图周围的可用空间。

对于视觉来说,想象蓝色方块是一个转换的UIView 。 视图周围的蓝色边框代表框架。 注意,即使视图被转换了,它的框架仍然没有被转换,处于标准的位置。 绿色区域表示如果通过frame而不是bounds可触摸的bounds

帧

另一方面,边界表示接收者相对于自身的矩形,考虑到转换,因此通过传递边界(在-convertPoint:toView: call之后)在视图中testing点将正确地返回给定的给定触摸(点)与视图相交。

这里是代码,viewB是目标视图,viewA是包含点的源视图。

 if(CGRectContainsPoint(viewB.bounds, [viewA convertPoint:point toView:viewB])){ //... } 

我想出了这个答案,因为我想要一个完整的代码响应解释。 如果任何人需要代码,为了完整起见,这是我最终计算如果一个视图(容器视图)完全包含在另一个视图(视图)中:

 -(BOOL)viewIsFullyContained:(UIView*)view{ // get the inner rectangle corners in the view coordinate system CGPoint upperLeft = [self.containerView convertPoint:self.containerView.bounds.origin toView:view]; CGPoint upperRight = [self.containerView convertPoint:CGPointMake(self.containerView.bounds.origin.x + self.containerView.bounds.size.width, self.containerView.bounds.origin.y) toView:view]; CGPoint lowerLeft = [self.containerView convertPoint:CGPointMake(self.containerView.bounds.origin.x, self.containerView.bounds.origin.y + self.containerView.bounds.size.height) toView:view]; CGPoint lowerRight = [self.containerView convertPoint:CGPointMake(self.containerView.bounds.origin.x + self.containerView.bounds.size.width, self.containerView.bounds.origin.y + self.containerView.bounds.size.height) toView:view]; // Check whether all of the corners are fully contained in the view. BOOL upperLeftIsContained = CGRectContainsPoint(view.bounds, upperLeft); BOOL upperRightIsContained = CGRectContainsPoint(view.bounds, upperRight); BOOL lowerLeftIsContained = CGRectContainsPoint(view.bounds, lowerLeft); BOOL lowerRightIsContained = CGRectContainsPoint(view.bounds, lowerRight); NSLog(@"Checking for (%i/%i/%i/%i)",upperLeftIsContained,upperRightIsContained,lowerLeftIsContained,lowerRightIsContained); return (upperRightIsContained && upperRightIsContained && lowerRightIsContained && lowerLeftIsContained); }