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;
}
發佈了51 篇原創文章 · 獲贊 873 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章