指向旋转的CGRect内部 [英] Point inside a rotated CGRect

查看:70
本文介绍了指向旋转的CGRect内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would you properly determine if a point is inside a rotated CGRect/frame?

框架与Core Graphics一起旋转。

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.

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

The frame being rotated is a regular UIView with a few subviews.

推荐答案

让我们假设您使用 transform 属性以旋转视图:

Let's imagine that you use transform property to rotate a view:

self.sampleView.transform = CGAffineTransformMakeRotation(M_PI_2 / 3.0);

如果您有手势识别器,例如,您可以查看用户是否在该位置点击在旋转视图中使用 locationInView ,它会自动为您考虑旋转:

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");
}

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

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.

这篇关于指向旋转的CGRect内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆