ノラプログラマーの技術メモ

ネットで調べても出てこなかった情報を載せていきたい技術系ブログ。

cocos2d-xでiPhoneとAndroidのマルチ解像度に対応する

問題

iPhoneは4系と5系で解像度が決まっているけれど、Androidは端末ごとでバラバラ。アプリを作ろうとすると、どうしてもマルチディスプレイ問題を解決する必要がある。

環境

windows8.1
cocos2d-x v2.2.3

解決方法

AppDelegate.cppのapplicationDidFinishLaunching関数に次の1行(pEGLView->setDesignResolutionSize)を入れる。

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);
	
    // マルチ解像度対応
    pEGLView->setDesignResolutionSize(480, 320, kResolutionShowAll);

    // turn on display FPS
    pDirector->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // create a scene. it's an autorelease object
    CCScene *pScene = HelloWorld::scene();

    // run
    pDirector->runWithScene(pScene);

    return true;
}

このままでも対応できているけど、Retinaのような解像度が高いディスプレイで表示すると画像が伸ばされるのでボヤけた感じに見える。

これを解消するにはリソースを2つに分けて、低解像度のものと高解像度のものを作る必要がある。もしリソースを2つに分けたのなら、AppDelegate.cppを次のように修正する。

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    CCDirector* pDirector = CCDirector::sharedDirector();
    CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

    pDirector->setOpenGLView(pEGLView);
	
    // マルチ解像度対応
    pEGLView->setDesignResolutionSize(480, 320, kResolutionShowAll);
    CCSize frameSize = pEGLView->getFrameSize();
    std::vector< std::string > searchPath;
    if (frameSize.height >= 640.0f ) {
        searchPath.push_back("hd");
        pDirector->setContentScaleFactor(2.0f);
    } else {
        searchPath.push_back("sd");
    }
    CCFileUtils::sharedFileUtils()->setSearchPaths(searchPath);

    // turn on display FPS
    pDirector->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);

    // create a scene. it's an autorelease object
    CCScene *pScene = HelloWorld::scene();

    // run
    pDirector->runWithScene(pScene);

    return true;
}

この辺はCocos2d-x:絶対にわかるマルチ解像度(マルチディスプレイ)対応 | Cocoa部に書かれている説明がとても分かりやすいので参考にしてみてください。