笔记:横竖屏切换

记录并积累开发过程中的小问题。请多指教。
由于是直接从微信复制过来,图片加载不出来,代码格式有点乱·····请见谅
更多笔记请扫码访问公众号,一起交流~

Step 1

适配的UI加上widget

Step 2

撸代码

//V H
setOrientation(dir)
{
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod('org/cocos2dx/javascript/AppActivity', 'setOrientation', '(Ljava/lang/String;)V', dir);

    } else if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod('AppController', 'setOrientation:', dir);
    }

    let frameSize = cc.view.getFrameSize();

    if (dir == 'V') {
        cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT);
        if (frameSize.width > frameSize.height) {
            cc.view.setFrameSize(frameSize.height, frameSize.width);
        }
        cc.Canvas.instance.designResolution = cc.size(750, 1334);
    } else {
        cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE);
        if (frameSize.height > frameSize.width) {
            cc.view.setFrameSize(frameSize.height, frameSize.width);
            cc.Canvas.instance.designResolution = cc.size(1334, 750);
        }
    }

    if (CC_JSB) {
        window.dispatchEvent(new cc.Event.EventCustom('resize', true));    
    }
}

Step 3

Android部分

构建时设备方向为游戏初始方向

修改AppActivity.java文件

public static void setOrientation(String dir){
    if(dir.equals("V")) {
        ((AppActivity)(SDKWrapper.getInstance().getContext())).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    } else {
        ((AppActivity) (SDKWrapper.getInstance().getContext())).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }
}

Step 4

ios部分

构建时设备方向为游戏初始方向

ios工程设备方向也为游戏初始方向,不需要添加其他的

修改AppController.mm文件

UIInterfaceOrientationMask orientation = UIInterfaceOrientationMaskLandscape;

  • (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return orientation;
    }
  • (void)setOrientation:(NSString*)dir {
    if ([dir isEqualToString:@“V”]) {
    orientation = UIInterfaceOrientationMaskPortrait;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@“orientation”];
    } else {
    orientation = UIInterfaceOrientationMaskLandscape;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@“orientation”];
    }
    }
6赞

不讲一下原理么

emmm
好像一直都懒得讲,嗯,我整理下,把原理都补一下

这没啥原理吧

mark

要说原理的话,确实没啥原理,cc的UI做好适配,然后去调用原生的方法就行

我是1.10.1的引擎 IDE能跳转到dispatchEvent中 但是运行的时候回报错:window.dispatchEvent is not a function 求大佬解惑

这个你看下引擎ccwidgetmanager.js 做一下修改即可