甘いものが好きです

iOS App開発時に感じた疑問や課題、その他の雑感などを書いていきます。

cocos2d for iPhone(Ver. 0.99.5)でRetinaディスプレイ対応

cocos2d for iPhoneを利用したiPhone AppでRetinaディスプレイ対応するための方法をメモしておく。対象バージョンについての記載が特にない限り、現時点で公開されている最新バージョンのVer. 0.99.5における方法とする。また、Retinaディスプレイと区別するために、それ以外のiPhone/iPod touchのディスプレイを「低解像度ディスプレイ」と呼ぶことにする。

Retinaディスプレイ対応についてはcocos2d for iPhoneリリースノートおよびプログラミングガイドに記載がある。以下はそれらに沿ってRetinaディスプレイ対応を行った際の具体的手順である。

デフォルトではRetinaディスプレイ非対応?

通常、iPhone AppでRetinaディスプレイ対応を行うためには、低解像度ディスプレイ用のある画像ファイルに対応する、Retinaディスプレイ対応用の高解像度画像ファイルには、「@2x」というサフィックスをつける。例えば、低解像度ディスプレイ用の画像「character.png」に対応する高解像度画像の名前は「character@2x.png」というように。このような規則で画像ファイル名を設定しておき、それをスプライトやメニューアイテムに設定してみると次のようになる。



これが低解像度ディスプレイでの表示。



これがRetinaディスプレイでの表示。スプライトやメニューアイテムの表示が大きくなってしまっている。

ファイル名の変更

この原因は実はファイルの命名にある。cocos2d for iPhoneのプログラミングガイドによると、cocos2dはAppleの慣習とは異なり、Retinaディスプレイ対応の画像ファイル名に独自のサフィックス「-hd」を使用する。なお、このサフィックスはccConfig.h内で次のように定義されている。

#define CC_RETINA_DISPLAY_FILENAME_SUFFIX @"-hd"

このため、スプライトやメニューアイテム等に使用する画像ファイルにおいては、Retinaディスプレイ対応ファイルのサフィックスを「@2x」ではなく「-hd」にしておかなければならない。ただし、アプリケーションのアイコンの画像や、アプリケーション起動時に表示するDefault.pngは、cocos2dがロードされる前に使用されるものなので、通常通りサフィックス「@2x」を使う。

cocos2dがサフィックスを使用して対象の画像ファイルを選択し読み込む手順がプログラミングガイドに記載されている。参考までにここに抜粋しておく。

Example: If you try to open the file “sprite.png” when RetinaDisplay mode is enabled, then the following will happen:

  1. Obtain the full path of “sprite.png” → ”/Volumes/XXX/sprite.png”
  2. Is the Application in Retina Display mode ?. If not, then return the fullpath name. If yes, then continue with step 3.
  3. Does “sprite.png” have the ”-hd” suffix ?
  4. In this case particular case, the answer is No, so it will try append the ”-hd” suffix to “sprite.png” → “sprite-hd.png”
  5. Does the HD image exist (”/Volumes/XXX/sprite-hd.png”) ?
  6. If it does exist it will use it, otherwise it will use the non-hd image

Same example, but trying to open the file “sprites-hd.plist”

  1. Obtain the full path of “sprites-hd.plist” → ”/Volumes/XXX/sprites-hd.plist”
  2. Is the Application in Retina Display mode ?. If not, then return the fullpath name. If yes, then continue with step 3.
  3. Does “sprites-hd.plist” have the ”-hd” suffix ?
  4. Yes. So, try to use it.

コード上でRetina対応可とする

画像ファイルのサフィックスを修正しただけでは、Retinaディスプレイ対応は完了しない。Retinaディスプレイ対応はコード上で指定しなければ有効にならないからだ。

テンプレートからcocos2d for iPhoneのアプリケーションを作成している場合、アプリケーションデリゲートクラスのapplicationDidFinishLaunching:メソッド中でコメントアウトされた次のような部分がある。

//// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
//if( ! [director enableRetinaDisplay:YES] )
//    CCLOG(@"Retina Display Not supported");

このコメントアウトを外してenableRetinaDisplay:を呼ぶことによりRetinaディスプレイ対応を有効にする。以上の手順により、cocos2d for iPhoneを利用したアプリケーションのRetinaディスプレイ対応は完了だ。