I have a simple screen in my iPhone app where I want a rectangle of 320×100 at the bottom of the screen to capture a touch. Here is my code inside touchesBegan:withEvent:
for (UITouch *touch in touches) {
CGPoint touchPoint = [touch locationInView:self.view];
NSLog(@"touch @ %f, %f", touchPoint.x, touchPoint.y);
// build a rectangle where we want to capture a URL tap
CGRect rectangle = CGRectMake(0, 480, 320, 100);
NSLog(@"midX, midY = %f, %f", CGRectGetMidX(rectangle), CGRectGetMidY(rectangle));
// check to see if they tapped the URL
if (CGRectContainsPoint(rectangle, touchPoint)) {
NSLog(@"You touched inside the rectangle.");
}
}
Now this code does not work as intended…the log from the mid point of the rectangle shows that my rectangle is built at midX, midY = 160.000000, 530.000000. According to the CGPoint documentation, the origin (0, 480) is the lower left-hand corner, but this is acting like the origin is the upper left-hand corner.
When I change the origin of my rectangle to 0, 380, everything works as intended. Maybe I’m not properly caffeinated yet this morning, but why am I seeing this discrepancy between the documentation and the execution?
Whether the origin is in the upper-left or lower-left corner really depends on the coordinates system.
In UIKit, the (0, 0) is in the upper-left corner, and the y-axis grows downwards.
In CoreGraphics, the (0, 0) is in the lower-left corner, and the y-axis grows upwards. To accommodate CG to UIKit a vertical reflection is applied by default, which is why if you draw an image or string directly using the CG functions in
-drawRect:you’ll get them upside-down.In your case, you’re getting points and rectangles from UIKit APIs, so the origin is in the upper-left corner.