【问题标题】:Flutter can't set CameraPreview widget to match screen sizeFlutter 无法将 CameraPreview 小部件设置为匹配屏幕尺寸
【发布时间】:2019-07-18 08:35:05
【问题描述】:

How to set Flutter CameraPreview Size "Fullscreen"

问题与此链接相同,但该解决方案不适用于我的手机 (LG G5)。在后置摄像头的摄像头预览周围留有黑色边距,但对于前置摄像头来说效果很好,但这次录制的视频将覆盖比预览视频更大的区域。我在其他手机上试过前后摄像头预览效果很好,但实际录制的视频覆盖更多区域的问题仍然存在。

编辑:问题源于相机包本身,而不是任何有类似问题的人的框架。

进一步调查和使用包发现,从包返回的纵横比值不能保证与设备的纵横比匹配,但在大多数情况下都可以正常工作。

 final size = MediaQuery.of(context).size;
    final deviceRatio = size.width / size.height;
    return Scaffold(
      key: _scaffoldKey,
      body: Stack(
        children: <Widget>[
          controller != null
              ? Center(
                  child: Transform.scale(
                    scale: controller.value.aspectRatio / deviceRatio,
                    child: new AspectRatio(
                      aspectRatio: controller.value.aspectRatio,
                      child: new CameraPreview(controller),
                    ),
                  ),
                )
              : Container(),
void onNewCameraSelected(CameraDescription cameraDescription) async {
    if (controller != null) {
      await controller.dispose();
    }
    controller = CameraController(
      cameraDescription,
      ResolutionPreset.high,
      enableAudio: enableAudio,
    );

    // If the controller is updated then update the UI.
    controller.addListener(() {
      if (mounted) setState(() {});
      if (controller.value.hasError) {
        showInSnackBar('Camera error ${controller.value.errorDescription}');
      }
    });

    try {
      await controller.initialize();
    } on CameraException catch (e) {
      _showCameraException(e);
    }

    if (mounted) {
      setState(() {
        print("controller inited");
      });
    }
  }

【问题讨论】:

    标签: flutter dart flutter-plugin


    【解决方案1】:

    这是来自文档的完全相同的代码,没有使用比例或比例,它在我拥有的每台设备上都可以正常工作,包括模拟器

    import 'dart:async';
    import 'dart:io';
    
    import 'package:camera/camera.dart';
    import 'package:flutter/material.dart';
    import 'package:path/path.dart' show join;
    import 'package:path_provider/path_provider.dart';
    
    Future<void> main() async {
      // Obtain a list of the available cameras on the device.
      final cameras = await availableCameras();
    
      // Get a specific camera from the list of available cameras.
      final firstCamera = cameras.first;
    
      runApp(
        MaterialApp(
          theme: ThemeData.dark(),
          home: TakePictureScreen(
            // Pass the appropriate camera to the TakePictureScreen widget.
            camera: firstCamera,
          ),
        ),
      );
    }
    
    // A screen that allows users to take a picture using a given camera.
    class TakePictureScreen extends StatefulWidget {
      final CameraDescription camera;
    
      const TakePictureScreen({
        Key key,
        @required this.camera,
      }) : super(key: key);
    
      @override
      TakePictureScreenState createState() => TakePictureScreenState();
    }
    
    class TakePictureScreenState extends State<TakePictureScreen> {
      CameraController _controller;
      Future<void> _initializeControllerFuture;
    
      @override
      void initState() {
        super.initState();
        // To display the current output from the Camera,
        // create a CameraController.
        _controller = CameraController(
          // Get a specific camera from the list of available cameras.
          widget.camera,
          // Define the resolution to use.
          ResolutionPreset.medium,
        );
    
        // Next, initialize the controller. This returns a Future.
        _initializeControllerFuture = _controller.initialize();
      }
    
      @override
      void dispose() {
        // Dispose of the controller when the widget is disposed.
        _controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Take a picture')),
          // Wait until the controller is initialized before displaying the
          // camera preview. Use a FutureBuilder to display a loading spinner
          // until the controller has finished initializing.
          body: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the Future is complete, display the preview.
                return CameraPreview(_controller);
              } else {
                // Otherwise, display a loading indicator.
                return Center(child: CircularProgressIndicator());
              }
            },
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.camera_alt),
            // Provide an onPressed callback.
            onPressed: () async {
              // Take the Picture in a try / catch block. If anything goes wrong,
              // catch the error.
              try {
                // Ensure that the camera is initialized.
                await _initializeControllerFuture;
    
                // Construct the path where the image should be saved using the
                // pattern package.
                final path = join(
                  // Store the picture in the temp directory.
                  // Find the temp directory using the `path_provider` plugin.
                  (await getTemporaryDirectory()).path,
                  '${DateTime.now()}.png',
                );
    
                // Attempt to take a picture and log where it's been saved.
                await _controller.takePicture(path);
    
                // If the picture was taken, display it on a new screen.
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DisplayPictureScreen(imagePath: path),
                  ),
                );
              } catch (e) {
                // If an error occurs, log the error to the console.
                print(e);
              }
            },
          ),
        );
      }
    }
    
    // A widget that displays the picture taken by the user.
    class DisplayPictureScreen extends StatelessWidget {
      final String imagePath;
    
      const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Display the Picture')),
          // The image is stored as a file on the device. Use the `Image.file`
          // constructor with the given path to display the image.
          body: Image.file(File(imagePath)),
        );
      }
    }
    

    【讨论】:

    • 是的,它在我的设备上也能正常工作,但我无法让它在我的小部件树中工作,我目前正在调查它。
    • 我让它适用于后置摄像头,但前置摄像头现在有一个拉伸预览。
    • 很高兴听到这个消息,现在你可能想尝试只为前置摄像头设置比例。
    • 如果我设置了比例,前置摄像头也可以工作,但这次实际录制的视频将覆盖更多区域,然后是前置摄像头的预览,仍在尝试找出解决方法。
    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2022-06-13
    • 2019-11-24
    • 2019-05-11
    相关资源
    最近更新 更多