Saltar al contenido

Empezando

  1. Instalar el paquete

    Ventana de terminal
    npm i @capgo/capacitor-screen-orientation
  2. Sincronización con proyectos nativos

    Ventana de terminal
    npx cap sync
  3. 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>
import { ScreenOrientation } from '@capgo/capacitor-screen-orientation';
// Get current orientation
const current = await ScreenOrientation.orientation();
console.log('Current orientation:', current.type);
// Lock to landscape
await ScreenOrientation.lock({ orientation: 'landscape' });
// Unlock orientation
await ScreenOrientation.unlock();
// Listen for orientation changes
const listener = await ScreenOrientation.addListener(
'screenOrientationChange',
(result) => {
console.log('Orientation changed:', result.type);
}
);

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 tracking
await ScreenOrientation.startOrientationTracking({
bypassOrientationLock: true
});
// Now orientation change events will reflect physical orientation
const listener = await ScreenOrientation.addListener(
'screenOrientationChange',
(result) => {
console.log('Physical orientation:', result.type);
}
);
// Check if orientation lock is enabled
const 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 done
await ScreenOrientation.stopOrientationTracking();

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

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'

Desbloquea la orientación de la pantalla.

await ScreenOrientation.unlock();

Start tracking physical device orientation using motion sensors.

await ScreenOrientation.startOrientationTracking({
bypassOrientationLock: true
});

Detener el seguimiento de orientación basado en movimiento.

await ScreenOrientation.stopOrientationTracking();

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 done
await listener.remove();

Elimine todos los detectores de eventos.

await ScreenOrientation.removeAllListeners();
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();
}
}
}
  • Uses Core Motion framework for physical orientation detection
  • Requires NSMotionUsageDescription in Info.plist for motion sensors
  • Soporte completo para todos los tipos de orientación.
  • 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