开发者

Origin of Rectangle in CGRectMake

I have a simple screen in my iPhone app where I want a rectangle of 320x100 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.开发者_StackOverflow");
    }        
}

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.


My documentation, too, does say lower-left corner. But I think this is an error in the documentation. (AFAIK, this is correct for the Mac desktop, so they probably just missed this when porting over the docs.)

On the iPhone, the origin is definitely the upper-left corner

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜