Empezando
-
Instalar el paquete
Ventana de terminal npm i @capgo/capacitor-screen-orientationVentana de terminal pnpm add @capgo/capacitor-screen-orientationVentana de terminal yarn add @capgo/capacitor-screen-orientationVentana de terminal bun add @capgo/capacitor-screen-orientation -
Sincronización con proyectos nativos
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync -
iOS Configuración (opcional) Para detectar la orientación física del dispositivo usando sensores de movimiento en iOS, agregue a su
Info.plist:<key>NSMotionUsageDescription</key><string>This app uses motion sensors to detect device orientation.</string>
Uso básico
Section titled “Uso básico”import { ScreenOrientation } from '@capgo/capacitor-screen-orientation';
// Get current orientationconst current = await ScreenOrientation.orientation();console.log('Current orientation:', current.type);
// Lock to landscapeawait ScreenOrientation.lock({ orientation: 'landscape' });
// Unlock orientationawait ScreenOrientation.unlock();
// Listen for orientation changesconst listener = await ScreenOrientation.addListener( 'screenOrientationChange', (result) => { console.log('Orientation changed:', result.type); });Detección de orientación física
Section titled “Detección de orientación física”Este complemento tiene una característica única: puede detectar la verdadera orientación física del dispositivo mediante sensores de movimiento, incluso cuando el usuario ha habilitado el bloqueo de orientación en su dispositivo.
import { ScreenOrientation } from '@capgo/capacitor-screen-orientation';
// Start motion-based trackingawait ScreenOrientation.startOrientationTracking({ bypassOrientationLock: true});
// Now orientation change events will reflect physical orientationconst listener = await ScreenOrientation.addListener( 'screenOrientationChange', (result) => { console.log('Physical orientation:', result.type); });
// Check if orientation lock is enabledconst lockStatus = await ScreenOrientation.isOrientationLocked();if (lockStatus.locked) { console.log('User has orientation lock enabled'); console.log('Physical:', lockStatus.physicalOrientation); console.log('UI:', lockStatus.uiOrientation);}
// Stop tracking when doneawait ScreenOrientation.stopOrientationTracking();API Referencia
Section titled “API Referencia”orientación()
Section titled “orientación()”Obtenga la orientación actual de la pantalla.
const result = await ScreenOrientation.orientation();// Returns: { type: OrientationType }Valores de tipo de orientación:
'retrato-primario'- Retrato, botón de inicio en la parte inferior- “retrato-secundario” - Retrato, al revés
'landscape-primary'- Landscape, home button on right'landscape-secondary'- Landscape, home button on left
bloquear (opciones)
Section titled “bloquear (opciones)”Bloquea la pantalla con una orientación específica.
interface OrientationLockOptions { orientation: OrientationLockType; bypassOrientationLock?: boolean; // Enable motion tracking}
await ScreenOrientation.lock({ orientation: 'landscape' });Valores de OrientationLockType:
'cualquiera'- Cualquier orientación'natural'- Orientación natural del dispositivo'paisaje'- Cualquier modo horizontal- “retrato” - Cualquier modo retrato
'retrato-primario'/'retrato-secundario''landscape-primary'/'landscape-secondary'
desbloquear()
Section titled “desbloquear()”Desbloquea la orientación de la pantalla.
await ScreenOrientation.unlock();startOrientationTracking(¿opciones?)
Section titled “startOrientationTracking(¿opciones?)”Start tracking physical device orientation using motion sensors.
await ScreenOrientation.startOrientationTracking({ bypassOrientationLock: true});detener el seguimiento de orientación()
Section titled “detener el seguimiento de orientación()”Detener el seguimiento de orientación basado en movimiento.
await ScreenOrientation.stopOrientationTracking();estáOrientaciónBloqueada()
Section titled “estáOrientaciónBloqueada()”Compruebe si el bloqueo de orientación del dispositivo está habilitado.
const result = await ScreenOrientation.isOrientationLocked();// Returns: {// locked: boolean,// physicalOrientation?: OrientationType,// uiOrientation?: OrientationType// }addListener(nombre del evento, devolución de llamada)
Section titled “addListener(nombre del evento, devolución de llamada)”Escuche los cambios de orientación.
const listener = await ScreenOrientation.addListener( 'screenOrientationChange', (result) => { console.log('New orientation:', result.type); });
// Remove when doneawait listener.remove();eliminarTodos los oyentes()
Section titled “eliminarTodos los oyentes()”Elimine todos los detectores de eventos.
await ScreenOrientation.removeAllListeners();Ejemplo completo
Section titled “Ejemplo completo”import { ScreenOrientation } from '@capgo/capacitor-screen-orientation';
class OrientationManager { private listener: any = null;
async init() { // Start motion tracking for physical orientation detection await ScreenOrientation.startOrientationTracking({ bypassOrientationLock: true });
// Listen for changes this.listener = await ScreenOrientation.addListener( 'screenOrientationChange', this.onOrientationChange.bind(this) );
// Get initial orientation const { type } = await ScreenOrientation.orientation(); console.log('Initial orientation:', type); }
onOrientationChange(result: { type: string }) { console.log('Orientation changed to:', result.type);
// Adjust UI based on orientation if (result.type.includes('landscape')) { this.showLandscapeUI(); } else { this.showPortraitUI(); } }
showLandscapeUI() { // Landscape-specific UI adjustments }
showPortraitUI() { // Portrait-specific UI adjustments }
async lockLandscape() { await ScreenOrientation.lock({ orientation: 'landscape' }); }
async lockPortrait() { await ScreenOrientation.lock({ orientation: 'portrait' }); }
async freeRotation() { await ScreenOrientation.unlock(); }
async checkIfUserHasOrientationLock() { const { locked, physicalOrientation, uiOrientation } = await ScreenOrientation.isOrientationLocked();
if (locked) { console.log(`Device is held in ${physicalOrientation} but UI shows ${uiOrientation}`); return true; } return false; }
async destroy() { await ScreenOrientation.stopOrientationTracking(); if (this.listener) { await this.listener.remove(); } }}Notas de plataforma
Section titled “Notas de plataforma”- Uses Core Motion framework for physical orientation detection
- Requires
NSMotionUsageDescriptionin Info.plist for motion sensors - Soporte completo para todos los tipos de orientación.
Android
Section titled “Android”- Uses accelerometer sensor for physical orientation detection
- No se requieren permisos adicionales
- Soporte completo para todos los tipos de orientación.
- Utiliza la orientación de la pantalla API
- La detección del sensor de movimiento es limitada
- Es posible que algunos navegadores no admitan todos los tipos de bloqueo