【问题标题】:Point inside a rotated CGRect点在旋转的 CGRect 内
【发布时间】:2013-06-08 18:03:10
【问题描述】:

如何正确确定一个点是否在旋转的 CGRect/框架内?

框架使用 Core Graphics 旋转。

到目前为止,我已经找到了一种算法,可以计算一个点是否在三角形内,但这并不是我所需要的。

被旋转的框架是一个带有几个子视图的常规 UIView。

【问题讨论】:

  • 你能解释一下“用 Core Graphics 旋转”吗?

标签: ios core-graphics cgrect


【解决方案1】:

假设您使用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 方法显然不需要在手势识别器中使用,而是可以在任何上下文中使用。但希望这能说明这项技术。

【讨论】:

  • 非常非常感谢。这就像一个魅力,只是不知道 iOS/UIKit 自己处理转换。再次感谢!
【解决方案2】:

使用CGRectContainsPoint()检查点是否在矩形内。

【讨论】:

  • 这不考虑轮换。矩形总是平行于 x 和 y 轴;如果您有一个旋转或倾斜的矩形(例如,在矢量图形应用程序中),您需要准确测试触摸是否在旋转的形状内,即使模型对象只有一个矩形。
猜你喜欢
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多