【问题标题】:Point not in Rect but CGRectContainsPoint says yes点不在 Rect 但 CGRectContainsPoint 说是
【发布时间】:2009-06-11 06:25:14
【问题描述】:

如果我有一个 UIImageView 并想知道用户是否点击了图像。在 touchesBegan 中,我执行以下操作,但始终以第一个条件结尾。窗口处于纵向模式,图像位于底部。我可以在窗口的右上角点一下,仍然进入第一个条件,这似乎很不正确。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:touch.view];

if(CGRectContainsPoint(myimage.frame, location) == 0){
//always end up here
}
else
{ //user didn't tap inside image}

值是:

location: x=303,y=102
frame: origin=(x=210,y=394) size=(width=90, height=15)

有什么建议吗?

【问题讨论】:

    标签: objective-c iphone cocoa-touch uiimageview core-graphics


    【解决方案1】:

    首先,您需要了解:

    UITouch *touch = [[event allTouches] anyObject];
    

    接下来,您要检查相对于图像视图的 locationInView。

    CGPoint location = [touch locationInView:self]; // or possibly myimage instead of self.
    

    接下来,CGRectContainsPoint 返回一个布尔值,因此将其与 0 进行比较是很奇怪的。应该是:

    if ( CGRectContainsPoint( myimage.frame, location ) ) {
       // inside
    } else {
       // outside
    }
    

    但是,如果 self 不是 myimage,那么 myimage 视图可能会得到触摸而不是你 - 从你的问题中不清楚它是什么对象 self 不是相关 UIImageView 的子类。

    【讨论】:

    • 不根据文档:developer.apple.com/documentation/graphicsimaging/... - “如果指定点位于指定矩形内,则返回 1;否则,返回 0。”将上面的代码与 self.view 一起使用是可行的,因为它是一个 UIViewController。谢谢。
    • 4thSpace:没错。它返回 0(因此等式成立),因为该点位于矩形之外。如果该点在矩形内,则 CGRectContainsPoint 将返回 true (1),并且相等性将是 false。
    • 我觉得值得一提的是,如果图像没有填满屏幕,这里提出的逻辑是行不通的。 [touch locationInView:self] 会给你一个相对于视图 x,y 坐标平面的点,而 myimage.frame 是相对于它的超级视图。
    • 假设是,我认为 myimage 是 self 的子视图,因此如果 locationInView:self 和 myImage.frame 在同一个坐标系中。使用 locatingInView:my image, and my image.bounds 可能是另一种可能性。
    【解决方案2】:

    你的逻辑简直颠倒了。 @987654321@ 方法返回布尔值,即“是”为 true。 True 不等于 0。

    【讨论】:

    • 0 在 C 中总是假的。在任何计算环境中它几乎从来都不是真的(我想不出任何使用 0 作为真的语言,尽管可能有一个)。
    • @Chuck:当然可以,但在某些情况下,0 确实表示“(某种)成功”(如 strcmp()),这就是我这样写的原因。
    猜你喜欢
    • 2021-11-19
    • 2015-07-14
    • 2023-04-09
    • 2015-03-30
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2012-05-11
    • 2016-10-28
    相关资源
    最近更新 更多