rotationForFrame function
CameraFrameRotation?
rotationForFrame({
- required int width,
- required int height,
- required int sensorOrientation,
- required bool isFrontCamera,
- required DeviceOrientation deviceOrientation,
Compute the rotation needed to present a camera frame upright to an on-device detection model, given the camera's sensor orientation and the device's current physical orientation.
- iOS: assumes the camera plugin pre-rotates the image stream per
AVCaptureConnection.videoOrientation(portrait-only path). Returns a rotation only when the device is in portrait and the frame arrived in landscape-sensor layout. - Android: combined
(sensor ± deviceRotation) % 360formula; the sign depends on front vs. back camera. - Other platforms (desktop / web): returns null;
camera_desktopand the web backend deliver already-upright frames.
Callers typically pass image.width / image.height from a
CameraImage, the camera's sensorOrientation (via
CameraDescription.sensorOrientation), and the effective device
orientation (via CameraController.value.deviceOrientation on mobile, or
a fallback based on MediaQuery when the controller is still
initializing).
Implementation
CameraFrameRotation? rotationForFrame({
required int width,
required int height,
required int sensorOrientation,
required bool isFrontCamera,
required DeviceOrientation deviceOrientation,
}) {
if (defaultTargetPlatform == TargetPlatform.iOS) {
final bool isPortrait =
deviceOrientation == DeviceOrientation.portraitUp ||
deviceOrientation == DeviceOrientation.portraitDown;
if (!isPortrait) return null;
if (height >= width) return null;
if (sensorOrientation == 90) return CameraFrameRotation.cw90;
if (sensorOrientation == 270) return CameraFrameRotation.cw270;
return null;
}
if (defaultTargetPlatform == TargetPlatform.android) {
final int deviceRotation = switch (deviceOrientation) {
DeviceOrientation.portraitUp => 0,
DeviceOrientation.landscapeLeft => 90,
DeviceOrientation.portraitDown => 180,
DeviceOrientation.landscapeRight => 270,
};
final int total = isFrontCamera
? (sensorOrientation + deviceRotation) % 360
: (sensorOrientation - deviceRotation + 360) % 360;
return switch (total) {
90 => CameraFrameRotation.cw90,
180 => CameraFrameRotation.cw180,
270 => CameraFrameRotation.cw270,
_ => null,
};
}
return null;
}