cocos creator - 动态修改设备屏幕方向

web:

web修改就比较简单了,直接调用cocos creater内置方法:cc.view.getFrameSize() 获取视图中边框尺寸,把宽和高交换一下就可以了,如下:

 changeOrientation:function(){
    let w = cc.view.getFrameSize().width;
    let h = cc.view.getFrameSize().height;
    cc.view.setFrameSize(h,w);
}

android和ios的就比较麻烦了,需要调用原生来修改,js如下:

js:
 changeOrientationH:function(isH){
    let w = cc.view.getFrameSize().width;
    let h = cc.view.getFrameSize().height;
    cc.view.setFrameSize(h,w);
    if (cc.sys.os == cc.sys.OS_IOS) {
        console.log("ios:");
        jsb.reflection.callStaticMethod('AppController',"changeOrientationH",isH);
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        console.log("android:");
        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "changeOrientationH", "(Z)V", isH);
    } 
}

Android:

// 设置屏幕方向
public static void changeOrientationH(boolean isH) {
    if (isH) {
        instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Log.d("横屏>>>>>", "SCREEN_ORIENTATION_LANDSCAPE: ");
    }else{
        instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Log.d("竖屏>>>>>", "SCREEN_ORIENTATION_LANDSCAPE: ");
    }
}

IOS:

AppComtorller.mm加这个函数

// 设置屏幕方向
+(void) setOrientation:(NSNumber *) orientation {
    NSNumber *orientationTarget;
    NSNumber * landscape = [NSNumber numberWithInt:1];
    NSNumber * portrait = [NSNumber numberWithInt:2];
    if ([orientation isEqualToNumber:landscape]) {
    orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    } else if ([orientation isEqualToNumber:portrait]){
    orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

RootViewController.mm

+(void) setCurOrientation:(NSNumber * ) orientation {
    curOrientation = orientation;
}
// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
//这是修改原来的函数,不是新加的
(NSUInteger) supportedInterfaceOrientations{
    NSNumber * landscape = [NSNumber numberWithInt:1];
    if ([curOrientation isEqualToNumber:landscape]) {
        return UIInterfaceOrientationMaskLandscape;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
//return UIInterfaceOrientationMaskAllButUpsideDown;
//return UIInterfaceOrientationMaskLandscape;
}
发布了50 篇原创文章 · 获赞 864 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_28299311/article/details/102960904