开发者

Simple if statement for checking whether a co-ordinate is inside a square?

开发者 https://www.devze.com 2022-12-23 08:31 出处:网络
I have an UIImageView and taking the raw touch input. I need to check if a touch is within a certain set of squares. At the moment...

I have an UIImageView and taking the raw touch input. I need to check if a touch is within a certain set of squares. At the moment...

I have this if statement....

if(46 < touchedAt.x && touchedAt.x < 124 && 18 < touchedAt.y && touchedAt.y < 75)

but I have tried to simplify it to this one...

if开发者_开发技巧(46 < touchedAt.x < 124 && 18 < touchedAt.y < 75)

It didn't work. Is it possible to simplify like this or am I stuck with the slightly lengthier version at the top? Is there a reason why the types of comparisons in the bottom if don't work?


I think a better solution would be to use CGRectContainsPoint:

CGRect rect = CGRectMake(46, 18, 124 - 46, 75 - 18);
if (CGRectContainsPoint(rect, touchedAt))
   // do whatever


Some languages support the "simple" version (Python, for example) but the C family doesn't.

In C family languages, the comparison operators are binary operators that return a boolean. One operator, two parameters, one result. Try to add another comparison and you end up comparing your boolean result against the next value. That's why you need all the && operators.

I don't know Objective-C, but I assume it does what C does.

To simplify, just write a simple function (perhaps inline) called "bounds_check" or "range_check" or similar that takes three parameters. Or better still, use one that's already written.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号