Search code examples
objective-cxcode4cocos2d-iphoneiphone-4

Retina Display coordinate is wrong


I try to display image to the Screen at Retina iPhone. So I used this code.

#define ScreenWidth 960
#define ScreenHeight 640

void ConvertCoordf(float* x, float* y)  
{  
    int height = ScreenHeight;  
    if ( height / 2 > *y )  
        *y += (height / 2 - *y) * 2;  
    else if ( height / 2 < *y )  
        *y -= (*y - height / 2) * 2;      
}

void DISPLAY_UPDATE(char *name, int x , int y , int startx, int starty , int w , int h ,float rotation)  
{  
    CCSprite *sprite = [[CCSprite spriteWithFile:[NSString stringWithUTF8String:name] rect:CGRectMake(startx, starty, w, h)] retain];  
    float drawX = x, drawY = y;   
    CGSize size = [sprite contentSize];

    int nWidth = size.width;
    int nHeight = size.height;
    drawX = drawX + nWidth/2;
    drawY = drawY - nHeight/2;

    ConvertCoordf(&drawX, &drawY);
    drawY -= nHeight;
    [sprite setPosition:ccp(drawX, drawY)];
    [sprite setAnchorPoint:CGPointMake(0.5, 0.5)];
    [sprite setRotation:rotation];
    [_mainLayer addChild:sprite];
    [sprite release];
}

Unfortunately, the image doesn't display correctly. The image's position is wrong. But in other iphone, it display correct. What's the matter? What's the problem in this coordinate convert?

Screenshots

enter image description here

enter image description here


Solution

  • This is completely wrong:

    #define ScreenWidth 960
    #define ScreenHeight 640
    

    The correct values of these macros:

    #define ScreenWidth 480
    #define ScreenHeight 320
    

    This is because you are not working with pixels. You are working with points and the system will calculate the pixels for you. This means the iPhone screen is always 480x320 points. You can also use pixels, but then you have to check the documentation.
    Soon I will add here a link to the description of this problem in the documentation.


    Edit added documentation link: Points Versus Pixels