About device orientation

本文介绍如何在iOS和Android上设置设备方向。提供了两种方法:OpenGL/cocos2d-x方式,适用于仅旋转由cocos引擎渲染的对象;ViewController方式(iOS)或通过XML设置(Android),适用于旋转UIKit对象或小部件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

About device orientation

This article describes how to set device orientation on iOS and android.
As you know, there are two ways to set device orientation:
  • The OpenGL / cocos2d-x way
    Faster, but doesn't rotate the UIKit objects(iOS) or widgets(android).
  • The ViewController way(iOS) or set by xml(android)
    A bit slower, but the UIKit objects(iOS) or widgets(android) are placed in the right place.

The OpenGL way

You can set device orientation as follows:

CCDirector::sharedDirector()->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);

This way can only rotate objects rendered by the cocos engine, such as sprites or labels.

ViewController way(iOS)

The device orientation takes effect as follows:
  • Tell the system which orientations the application supports(RootViewController.mm)
    // Override to allow orientations other than the default landscape orientation.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        return UIInterfaceOrientationIsLandscape( interfaceOrientation );
    }
    
  • Add the view OpenGL rendered to the root view controller(AppController.mm)
    // Use RootViewController manage EAGLView 
        viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
        viewController.wantsFullScreenLayout = YES;
        viewController.view = __glView;
    

The code is implemented in cocos2d-x as an iOS template.

Set device orientation in AndroidManifest.xml(android)

<application android:label="@string/app_name" android:debuggable="true" android:icon="@drawable/icon">
        <activity android:name=".ApplicationDemo" 
                  android:label="@string/app_name" 
                  android:screenOrientation="landscape" 
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 
                  android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Conclusions

1. If you want to use OpenGL approach in iOS, don't use RootViewController.
2. If you want to use OpenGL way in Android, set the orientation to portrait in AndroidManifest.xml.
3. If you don't use any UIKit objects(iOS) or widgets(android) at all, then using OpenGL directly will be faster.

Supporting multiple orientations

Apply the following workaround to support multiple orientations as of cocos2d-x v2.0.2.
This patch may not be supported in future releases of cocos2d-x, or may become partially deprecated.

iOS

1. Comment out assert(m_eResolutionPolicy  kResolutionUnKnown); in cocos2dx/platform/ios/CCEGLView.mm::setContentScaleFactor(...).
2. Comment out CCAssert(m_bIsRetinaEnabled  false, "can not enable retina while set design resolution size!"); in cocos2dx/platform/CCEGLViewProtocol.cpp::setDesignResolutionSize(...).
3. Return true in shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation.
4. In (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation, add:

CGSize s;
if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication.statusBarOrientation)) {
  s = CGSizeMake(std::max<float>(UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height), std::min<float>(UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height));
} else {
  s = CGSizeMake(std::min<float>(UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height), std::max<float>(UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height));
}

cocos2d::CCDirector* director = cocos2d::CCDirector::sharedDirector();
director->enableRetinaDisplay(false);
director->getOpenGLView()->setFrameSize(s.width, s.height);
director->getOpenGLView()->setDesignResolutionSize(s.width, s.height, kResolutionShowAll);
director->enableRetinaDisplay(true);

Android

1. Add nativeInit(w, h); to cocos2dx/platform/android/java/src_common/org/cocos2dx/lib/Cocos2dxRenderer.java -> void onSurfaceChanged(GL10 gl, int w, int h).
2. Add this code to void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thiz, jint w, jint h):

cocos2d::CCEGLView* view = cocos2d::CCDirector::sharedDirector()->getOpenGLView();
if (!view) {
  ...
} else {
  ...
  if (view->getFrameSize().width != w || view->getFrameSize().height != h) {
    view->setFrameSize(w, h);
    view->setDesignResolutionSize(w, h, kResolutionShowAll);
  }
}

#SceneScript Reference SceneScript is follows the ECMAScript 2018 specification, so you can utilize all functionalities from ECMAScript that you would also find in similar languages such as JavaScript. This is very useful as you can make use of various helpful classes. For example, allows you to access the current date and time, allows you to access various mathematical utility functions.DateMath This page only covers all additions that SceneScript adds to make working with wallpapers possible. #Globals SceneScript introduces a handful of globals which you can access at any point in your code. Global Description engine Access to general features of the application. class.IEngine input Input related data, mainly the mouse cursor. class.IInput thisScene The currently loaded scene wallpaper. classIScene thisLayer The layer this script has been loaded on. class.ILayer thisObject The object this script belongs to. class.IThisPropertyObject console Access the console log for debugging purposes. class.IConsole shared Empty by default, allows you to share data between multiple scripts. class.Shared #Events SceneScript uses an event system that allows you to run specific code whenever certain events take place. Most notably, the event is most commonly used to execute SceneScript code at every frame that Wallpaper Engine calculates. The event is good for running code once when the wallpaper is first loaded and the event allows you to react to changes to user properties of your wallpaper. Additionally, there are a handful of events which related to mouse movement and mouse input which you can incorporate into your wallpaper.updateinitapplyUserPropertiescursor Event Description init This initialization function will be called once after the object it belongs to has been created. update This event function will be called every frame for all scripts that export it. destroy This event function will be called just before the object it belongs to gets destroyed. resizeScreen This function will be called every time the wallpaper resizes because of a change to the current resolution. applyUserProperties This event function will be called once initially when the wallpaper is loaded and whenever any user properties are being adjusted by the user. cursorEnter This event function will be called when the cursor enters the bounds of the object. cursorLeave This event function will be called when the cursor leaves the bounds of the object. cursorMove This event function will be called when the cursor has been moved. cursorDown This event function will be called when the cursor is being pressed down on an object. cursorUp This event function will be called when the cursor is being released over an object. cursorClick This event function will be called when the cursor has been pressed and released on the same object. mediaStatusChanged This event function will be called when the media integration is turned on or off by the user. mediaPlaybackChanged This event function will be called when the users starts, stops or pauses media. mediaPropertiesChanged This event function will be called when the properties of the currently playing media change. mediaThumbnailChanged This event function will be called when the thumbnail of the currently playing media changes. mediaTimelineChanged This event function will be called when the current time of the playing media changes and is only provided by certain applications. #Classes All components of Wallpaper Engine are provided with a fitting class so that you can access everything programmatically. The following list contains all relevant classes introduced by SceneScript: Class Description AnimationEvent This object describes an animation event that has been fired from a timeline or puppet warp animation. AudioBuffers Provides access to the left and right audio spectrum values and their combined average for audio visualization purposes. CameraTransforms Objects of this class describe the camera orientation and position. CursorEvent Provides information about the cursor position during cursor events. IAnimation This class represents a timeline property animation. IAnimationLayer This class represents a puppet warp or 3D model animation layer. IConsole You can access this interface anywhere in your SceneScript code through the global object to interact with the console log.console IEffect Provides access to image effects used on image layers. IEffectLayer Base class for image and text layers. IEngine Provides general information about the user device and the running wallpaper. IImageLayer This class provides access to functions specific to image layers. ITextLayer This class provides access to functions specific to text layers. IModelLayer This class provides access to functions specific to 3D model layers. IInput Provides access to input related data, mainly the mouse cursor. ILayer Provides access to data related to a layer. ILocalStorage Provides access to the local storage functionality. IMaterial Provides access to dynamic properties of materials / shader properties. IParticleSystem Provides access to particle systems and lets you modify their playback state. IParticleSystemInstance Provides access to instance modifiers for particle systems. You can use this to adjust details of a particle system dynamically. IScene Provides access to properties of the currently loaded scene. ISoundLayer Provides access functions specific to sound layers. ITextureAnimation This class represents a texture animation. IVideoTexture This class represents a video texture animation. Mat4 Utility class used for creating a 4 dimensional identity matrix. MediaPlaybackEvent Media integration event, fired when the user starts, stops or pauses media. MediaPropertiesEvent Media integration event, fired when the properties of the current media session are changing. MediaStatusEvent Media integration event, fired when the user turns the media integration on or off. MediaThumbnailEvent Media integration event, fired when the thumbnail pertaining to the current media changes. MediaTimelineEvent Optional media integration event, fired irregularly when the current time of the media session changes. Shared Related to the global object which you may use to share data between multiple scripts.shared Vec2 Utility class which holds a 2 dimensional value pair: and .xy Vec3 Utility class which holds a 3 dimensional value pair: , and .xyz #Modules Wallpaper Engine also provides some modules which can be used to access certain utility functions. These can be helpful to easily implement certain use-cases. Module Description WEColor Module which provides utility functions related to color manipulation. WEMath Module which provides utility functions related to general mathematical functions. WEVector Module which provides utility functions related to working with vectors.我让你写的代码是在wallpaer引擎内使用的,这是他的语言参考
最新发布
08-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值