首先介紹一個api和相應的參數:
cc.view.setDesignResolutionSize(1024, 768, cc.ResolutionPolicy.FIXED_WIDTH);
這里設置游戲制作的目標尺寸和顯示的模式。
模式包括:
cc.ResolutionPolicy = { // The entire application is visible in the specified area without trying to preserve the original aspect ratio. // Distortion can occur, and the application may appear stretched or compressed. EXACT_FIT:0, // The entire application fills the specified area, without distortion but possibly with some cropping, // while maintaining the original aspect ratio of the application. NO_BORDER:1, // The entire application is visible in the specified area without distortion while maintaining the original // aspect ratio of the application. Borders can appear on two sides of the application. SHOW_ALL:2, // The application takes the height of the design resolution size and modifies the width of the internal // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios FIXED_HEIGHT:3, // The application takes the width of the design resolution size and modifies the height of the internal // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios FIXED_WIDTH:4, UNKNOWN:5 };
參考官方說明: http://www.cocos2d-x.org/wiki/Multi_resolution_support
EXACT_FIT會拉伸游戲,充滿整個屏幕,最簡單最粗暴;
SHOW_ALL保持游戲原比例,讓一邊占滿屏幕,另外一側黑邊;
NO_BORDER跟SHOW_ALL類似,但讓短邊占滿屏幕,另外一側超出屏幕,不顯示黑邊,一部分畫面在屏幕外,無法顯示;
FIXED_WIDTH和FIXED_HEIGHT都是NO_BORDER的升級版,指定那一側充滿屏幕,另外一側超出屏幕。
這里建議使用FIXED_WIDTH和FIXED_HEIGHT,其他用法請參考:
這兩個方案適合UI沿着屏幕邊緣布局,而游戲畫面居中,游戲背景則可以裁剪(顯示一部分)的情況。
通過上邊的文章,我們知道winSize,visibleSize,designSize(自己的設計尺寸)。
無論什么方案,winSize和visibleSize是一致的,cc.director.getWinSize()和cc.director.getVisibleSize()獲取到一樣的數據。
以FIXED_WIDTH為例
布局過程中,橫向就按照設計稿直接寫死絕對坐標值都可以,因為cc.director.getVisibleSize().width就是我們的設計寬度,cocos2d通過縮放會讓橫向剛好占滿屏幕;
而縱向,就利用cc.director.getVisibleSize().height來布局。
y=0表示剛好在屏幕邊緣,在FIXED_WIDTH方案中,不像NO_BORDER會有visibleOrigin,這里不需要考慮這個值,因為總是0,cocos2d自動把y=0放到這個visibleOrigin位置了。
而屏幕上方則使用cc.director.getVisibleSize().height - 20類似的方式來布局。
這里的20也會隨着整個畫面的壓縮比例而變小。
例如設計寬高為1024*768,但實際放到725*225的區域運行,那么cc.director.getVisibleSize()獲取到的是(1024, 315)左右。實際上這個尺寸並不是真實屏幕尺寸,但可以按照這個數值進行布局。
屏幕尺寸
另外cc.view.getFrameSize可以獲取屏幕尺寸