【问题标题】:CGRectIntersectsRect with 2 UIImageViews does not work带有 2 个 UIImageViews 的 CGRectIntersectsRect 不起作用
【发布时间】:2014-05-29 13:28:13
【问题描述】:

我有问题。

简而言之:CGRectIntersectsRect(object1.frame, object2.frame) 放在 UIViewController 中不适用于在不同类(Class1 和 Class2)中创建的 object1 和 object2。我只能更改它们的坐标,例如object1.center.xobject1.frame.size.width = 0(我想这就是CGRectIntersection 函数不起作用的原因)。这些对象只是相互穿过。

据我了解,它可能与协议/委托有关,但我没有找到任何足够的信息来解决我的情况。

Platform.m(我在 ViewController 中创建平台的类)

@implementation Platform

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        platformView = [[UIImageView alloc]initWithFrame:frame];
        platformView.image = [UIImage imageNamed:@"platform.png"];

        [self addSubview:platformView];

    }
    return self;
}

ViewController.m(@interface中有Platform *platform; Kelvin *kelvin;)

-(void)addPlatform
   {
    platform = [[Platform alloc]initWithFrame:CGRectMake(initialPlatformX, (500 -    arc4random()%200), 200, 10)];
    [self.view addSubview:platform];
   }

    **if (!CGRectIntersectsRect(kelvin.frame, platform.frame)) {
        NSLog(@"%f", platform.frame.size.width);
    }**

【问题讨论】:

  • 顺便说一句,你没有显示kelvin的创建。它是platform 的同一视图的子视图吗?如果它们不是同一视图的子视图,则必须将框架转换为相同的坐标系。

标签: ios objective-c uiimageview cgrect


【解决方案1】:

您的解释令人困惑且难以理解。

例如,这句话对我来说完全是个谜:

据我了解,它可能与协议/委托有关,但我 没有找到任何足够的信息来解决我的情况。

代表团?嗯?矩形不是对象。委托是对象的一种设计模式。这与这里有什么关系? (答案:很可能根本不相关。)

不过,继续前进,这里有几点需要考虑:

如果两个视图的框架都是同一视图的子视图,它们将仅使用相同的坐标系。你的平台和你的“开尔文”视图子视图也是同一个视图(看起来你直接将平台添加到视图控制器的内容视图中,那么你的“开尔文”视图也是视图控制器内容视图的子视图吗?)

另外,你参考object1.frame.size.width = 0

CGRectIntersectsRect 函数检查两个矩形的像素是否重叠。如果您的任何一个矩形的高度或宽度为 0,则它是空的,并且不能与任何东西相交。

【讨论】:

  • 谢谢!那是我的错误,“平台”和“开尔文”这两个对象是同一个视图的子视图,但不是直接的,我通过 CGRectMake(0, 0, frame.size.width, frame.size. height) 在这里使用 x 和 y 坐标,因此后来它们在相交时具有不同的坐标。现在我将它们的初始坐标都更改为 0, 0 并且它可以工作! =)
【解决方案2】:

initWithFrame 中,您使用PlatformframeUIImageView 子视图添加到Platform。这是不正确的。例如,如果您在CGRectMake(10, 10, 100, 100) 中添加PlatForm,那么您将在Platform 中的CGRectMake(10, 10, 100, 100) 添加图像视图(在原始视图中是CGRectMake(20, 20, 100, 100))。

所以,相反,我认为您想创建一个以0, 0 开头的CGRect(或使用Platformbounds,而不是frame):

@implementation Platform

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        platformView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        platformView.image = [UIImage imageNamed:@"platform.png"];

        [self addSubview:platformView];
    }
    return self;
}

顺便说一句,为了安全起见,您可能还想将 clipsToBounds 设置为 YES,这样如果您将 contentMode 更改为无法缩放以适应的东西,您就没有担心图像溢出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多