筆者所使用的方案經(jīng)歷了正式的線上項(xiàng)目使用喇勋,請放心食用
假設(shè)項(xiàng)目的設(shè)計(jì)分辨率為1920x1080
一酗钞、全平臺(tái)通用邏輯
無論是Android岸裙、IOS還是h5揩页,進(jìn)行橫豎屏切換旷偿,都需要執(zhí)行下面對應(yīng)代碼,
而h5執(zhí)行之后爆侣,就能完美適配橫豎屏切換了萍程。
Andriod、IOS 還需要一些其他的處理兔仰。
首先
// 獲取屏幕物理分辨率
let frameSize = cc.view.getFrameSize()
豎屏
cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT)?
if (frameSize.width > frameSize.height)
? ??????cc.view.setFrameSize(frameSize.height, frameSize.width)
// this.canvas 為當(dāng)前fire場景的畫板??
this.canvas.designResolution = cc.size(1080, 1920)
橫屏
cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE)
if (frameSize.height > frameSize.width)
? ??????cc.view.setFrameSize(frameSize.height, frameSize.width)
this.canvas.designResolution = cc.size(1920, 1080)
二茫负、Android原生處理
豎屏
// instance 為AppActivity,我的做法是做了對象?public static AppActivity instance乎赴,然后在 onCreate 賦值
instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
橫屏
// instance 為AppActivity忍法,我的做法是做了對象?public static AppActivity instance,然后在 onCreate 賦值
instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
上面的兩個(gè)函數(shù)榕吼,需要腳本層通過反射調(diào)用饿序。
三、IOS原生處理
// 首先羹蚣,將設(shè)備方向設(shè)為未知嗤堰,這段必要,否則直接切換橫豎屏度宦,有可能會(huì)切換失敗
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
float w = cocosView.bounds.size.width;
float h = cocosView.bounds.size.height;
豎屏
oMask = UIInterfaceOrientationMaskPortrait;
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
if (w > h){
? ??????cocosView.bounds = CGRectMake(0, 0, h, w);
}
橫屏
oMask = UIInterfaceOrientationMaskLandscape;
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
if (h > w){
? ??????cocosView.bounds = CGRectMake(0, 0, h, w);
}
最后不管橫豎屏
cocosView.center = CGPointMake(cocosView.frame.size.width * 0.5, cocosView.frame.size.height * 0.5);
四、Android告匠、IOS 通用腳本處理
?IOS戈抄、Android設(shè)備在屏幕旋轉(zhuǎn)的時(shí)候并不會(huì)觸發(fā)布局重新刷新,但是我們可以主動(dòng)調(diào)用事件觸發(fā)刷新
window.dispatchEvent(new cc.Event.EventCustom('resize', true))
為什么resize能刷新能后专,你可以在CCWidgetManager.js划鸽,找到如下代碼
init: function init(director) {
...
? ??if (cc.sys.isMobile) {
? ??????window.addEventListener('resize', this.onResized.bind(this));
? ? }
...
}
onResized: function onResized() {
? ??var scene = cc.director.getScene();
? ??if (scene) {
? ??????this.refreshWidgetOnResized(scene);
? ? }
}
更詳細(xì)的自己去跟蹤引擎代碼吧。
至此全平臺(tái)的屏幕旋轉(zhuǎn)實(shí)現(xiàn)戚哎。