How to set 3:4 Aspect Ratio Flutter camera preview

5,395

Solution 1

I solved my problem like this

final size = MediaQuery.of(context).size.width;

Transform.scale(
                scale: 1.0,
                child: AspectRatio(
                  aspectRatio: 3.0 / 4.0,
                  child: OverflowBox(
                    alignment: Alignment.center,
                    child: FittedBox(
                      fit: BoxFit.fitWidth,
                      child: Container(
                        width: size,
                        height: size / controller.value.aspectRatio,
                        child: Stack(
                          children: <Widget>[
                            CameraPreview(controller),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              )

Solution 2

RotatedBox(
              quarterTurns:
                  MediaQuery.of(context).orientation == Orientation.landscape
                      ? 3
                      : 0,
              child: Transform.scale(
                scale: 1.0,
                child: AspectRatio(
                  aspectRatio: 3.0 / 4.0,
                  child: OverflowBox(
                    alignment: Alignment.center,
                    child: FittedBox(
                      fit: BoxFit.fitWidth,
                      child: Container(
                        width: size,
                        height: size / cameraController.value.aspectRatio,
                        child: Stack(
                          children: <Widget>[
                            CameraPreview(cameraController),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            )
Share:
5,395
Gursewak Singh
Author by

Gursewak Singh

Innovative Android/Flutter and React-Native Developer with 5+ years of experience designing, developing, testing, and maintaining Android/Flutter applications.

Updated on December 16, 2022

Comments

  • Gursewak Singh
    Gursewak Singh over 1 year

    I am working on Flutter app. I need camera functionality and decided to use Camera Plugin for this. I set the Aspect Ratio 3:4 but the image is warped and smaller than it should be. I think there is problem with scale. What is the correct way to set camera Aspect Ratio (i.e 3:4).

    final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    final aspectRatio=3/4;
    
    Transform.scale(
            scale: controller.value.aspectRatio / deviceRatio,
            child: Center(
              child: AspectRatio(
                  aspectRatio: aspectRatio,
                  child: CameraPreview(controller),
              )
            ),
          )