深入理解Flutter相机插件【Flutter专题22】

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前面给大家讲解http包和dio包,涉及到一个知识点就是上传图片,那么图片哪里来?","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每个移动设备都带有一个内置的相机应用程序,用于捕捉图片、录制视频以及一些特定于每个设备的吸引人的功能。但是如果你正在开发一个需要相机访问的应用程序,那么你必须自己实现相机功能。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"你可能会问,当默认的相机应用程序已经可用时,为什么我需要再次实现相机功能?","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"答案是因为,如果您想提供适合您的应用的独特用户界面,或者添加设备默认相机应用中不存在的功能,那么它是必需的。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在本文中,您将学习使用支持 Android 和 iOS 平台的官方","attrs":{}},{"type":"link","attrs":{"href":"https://pub.dev/packages/camera","title":null,"type":null},"content":[{"type":"text","text":"camera包","attrs":{}}]},{"type":"text","text":"为 Flutter 应用程序实现基本的相机功能。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"应用概览","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在深入研究代码之前,让我们回顾一下我们将要构建的应用程序。最终的应用程序将包含大部分基本的相机功能,包括:","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"捕获清晰度选择器","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"变焦控制","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"曝光控制","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"闪光模式选择器","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"翻转摄像头的按钮——后摄像头到前摄像头,反之亦然","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用于捕获图像的按钮","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用于从图像模式切换到视频模式的切换","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"视频模式控制——开始、暂停、恢复、停止","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上次捕获的图像或视频预览","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"检索图像/视频文件","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"先看一眼最后的效果图。","attrs":{}}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/a5/a58326ef14a614b1394ad8128971122c.jpeg","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"入门","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"使用以下命令创建一个新的 Flutter 项目:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"flutter create flutter_camera_demo","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用自己喜欢的 IDE 打开项目,但在本示例中,我将使用 VS Code:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"code flutter_camera_demo","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"将以下依赖项添加到您的文件中:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"pubspec.yaml","attrs":{}}],"attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://pub.dev/packages/camera","title":null,"type":null},"content":[{"type":"text","text":"camera","attrs":{}}]},{"type":"text","text":" : 提供用于实现相机功能的跨平台 API","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://pub.dev/packages/video_player","title":null,"type":null},"content":[{"type":"text","text":"video_player","attrs":{}}]},{"type":"text","text":":用于预览捕获的视频","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"path_provider","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":":用于将图像或视频存储在目录中,可以轻松访问它们","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"dependencies: camera: ^0.8.1+7 videoplayer: ^2.1.14 path_provider: ^2.0.2","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"使用camera如果报错的话","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"尝试将 compileSdkVersion 和 targetSdkVersion 更新为 31。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b4/b470946e3167fb1204e0dc7e07903381.png","alt":"image-20211125150124416","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"将文件内容替换为以下内容:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"main.dart","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"import 'package:flutter/material.dart';\n​\nimport 'screens/camera_screen.dart';\n​\nFuture main() async {\n  runApp(MyApp());\n}\n​\nclass MyApp extends StatelessWidget {\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: 'Flutter Demo',\n      theme: ThemeData(\n        primarySwatch: Colors.blue,\n     ),\n      debugShowCheckedModeBanner: false,\n      home: CameraScreen(),\n   );\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"该","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"CameraScreen","attrs":{}}],"attrs":{}},{"type":"text","text":"将包含所有的相机功能的代码与它的用户界面一起。我们将稍后添加它,但在我们这样做之前,我们必须在设备上安装可用的摄像头。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"检索可用的相机","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在main.dart文件中,定义一个全局变量,称为我们将存储可用摄像机列表的位置。这将有助于我们以后轻松引用它们。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"`cameras","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"import 'package:camera/camera.dart';\n​\nList cameras = [];","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以在使用该方法初始化应用程序之前检索函数内部的相机——只需确保该函数是异步的,因为它必须等待检索设备的可用相机,并且通常 Flutter 的函数是一个简单的函数,只有调用:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"main()``availableCameras()``main()``runApp()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"Future main() async {\n  try {\n    WidgetsFlutterBinding.ensureInitialized();\n    cameras = await availableCameras();\n } on CameraException catch (e) {\n    print('Error in fetching the cameras: $e');\n }\n  runApp(MyApp());\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"初始化相机","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"创建一个名为camera_screen.dart的新文件并在其中定义有状态小部件CameraScreen。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"import 'package:camera/camera.dart';\nimport 'package:flutter/material.dart';\n​\nimport '../main.dart';\n​\nclass CameraScreen extends StatefulWidget {\n  @override\n  _CameraScreenState createState() => _CameraScreenState();\n}\n​\nclass _CameraScreenState extends State {\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为相机定义一个控制器,为","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"isCameraInitialized","attrs":{}}],"attrs":{}},{"type":"text","text":"布尔变量定义一个值,您可以使用它来轻松了解相机是否已初始化并相应地刷新 UI:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"class _CameraScreenState extends State {\n  CameraController? controller;\n  bool _isCameraInitialized = false;\n​\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"控制器将帮助您访问相机的不同功能,但在使用它们之前,您必须初始化相机。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"创建一个名为 的新方法。此方法将有助于处理两种情况:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"numberedlist","attrs":{"start":"","normalizeStart":1},"content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"初始化一个新的相机控制器,这是启动相机屏幕所需要的","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"当用户翻转相机视图或改变相机清晰度时,处置之前的控制器并用具有不同属性的新控制器替换它","attrs":{}}]}]}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"class _CameraScreenState extends State {\n // ...\n\n void onNewCameraSelected(CameraDescription cameraDescription) async {\n final previousCameraController = controller;\n // Instantiating the camera controller\n final CameraController cameraController = CameraController(\n cameraDescription,\n ResolutionPreset.high,\n imageFormatGroup: ImageFormatGroup.jpeg,\n );\n\n // Dispose the previous controller\n await previousCameraController?.dispose();\n\n // Replace with the new controller\n if (mounted) {\n setState(() {\n controller = cameraController;\n });\n }\n\n // Update UI if controller updated\n cameraController.addListener(() {\n if (mounted) setState(() {});\n });\n\n // Initialize controller\n try {\n await cameraController.initialize();\n } on CameraException catch (e) {\n print('Error initializing camera: $e');\n }\n\n // Update the boolean\n if (mounted) {\n setState(() {\n _isCameraInitialized = controller!.value.isInitialized;\n });\n }\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在initState()","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"方法内部调用此函数并作为. 列表的第一个索引通常是设备的后置摄像头。","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"索引","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"0","attrs":{}}],"attrs":{}},{"type":"text","text":"的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"cameras","attrs":{}}],"attrs":{}},{"type":"text","text":"名单-后置摄像头","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"索引","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"1","attrs":{}}],"attrs":{}},{"type":"text","text":"的","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"cameras","attrs":{}}],"attrs":{}},{"type":"text","text":"名单-前置摄像头","attrs":{}}]}]}],"attrs":{}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"lass _CameraScreenState extends State {\n // ...\n\n @override\n void initState() {\n onNewCameraSelected(cameras[0]);\n super.initState();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"另外,不要忘记在相机未激活时释放方法中的内存:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"dispose()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"@override\nvoid dispose() {\n controller?.dispose();\n super.dispose();\n}\n ","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"处理相机生命周期状态","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在任何设备上运行相机都被认为是一项占用大量内存的任务,因此如何处理释放内存资源以及何时释放内存资源非常重要。应用程序的生命周期状态有助于了解状态变化,以便您作为开发人员可以做出相应的反应。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 Flutter 中,您可以通过添加","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"WidgetsBindingObserver","attrs":{}}],"attrs":{}},{"type":"text","text":" mixin 并管理生命周期更改。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"didChangeAppLifecycleState()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"class _CameraScreenState extends State\n with WidgetsBindingObserver {\n\n // ...\n\n @override\n void didChangeAppLifecycleState(AppLifecycleState state) {\n final CameraController? cameraController = controller;\n\n // App state changed before we got the chance to initialize.\n if (cameraController == null || !cameraController.value.isInitialized) {\n return;\n }\n\n if (state == AppLifecycleState.inactive) {\n // Free up memory when camera not active\n cameraController.dispose();\n } else if (state == AppLifecycleState.resumed) {\n // Reinitialize the camera with same properties\n onNewCameraSelected(cameraController.description);\n }\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold();\n }\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"添加相机预览","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"现在我们已经完成了相机状态的初始化和管理,我们可以定义一个非常基本的用户界面来预览相机输出。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Flutter 的camera 插件自带一个方法,调用显示camera 输出,用户界面可以定义如下:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"buildPreview()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"class _CameraScreenState extends State\n with WidgetsBindingObserver {\n\n // ...\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: _isCameraInitialized\n ? AspectRatio(\n aspectRatio: 1 / controller!.value.aspectRatio,\n child: controller!.buildPreview(),\n )\n : Container(),\n );\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"预览将如下所示:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/70/709840c9f84c464961bda281e75f4d41.png","alt":"相机预览","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您会注意到设备状态栏在顶部可见;您可以通过在方法中添加以下内容来隐藏它以防止它阻碍相机视图:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"initState()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"@override\nvoid initState() {\n // Hide the status bar\n SystemChrome.setEnabledSystemUIOverlays([]);\n\n onNewCameraSelected(cameras[0]);\n super.initState();\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"基本的相机预览已准备就绪!现在,我们可以开始向相机添加功能。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"添加清晰度选择器","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ResolutionPreset","attrs":{}}],"attrs":{}},{"type":"text","text":"来定义相机视图的清晰度。在初始化相机时,我们使用了.","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ResolutionPreset.high","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"要更改相机视图的清晰度,您必须使用新值重新初始化相机控制器。我们将在相机视图的右上角添加一个下拉菜单,用户可以在其中选择分辨率预设。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在类中添加两个变量,一个用于保存所有","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"ResolutionPreset","attrs":{}}],"attrs":{}},{"type":"text","text":"值,另一个用于存储","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"currentResolutionPreset","attrs":{}}],"attrs":{}},{"type":"text","text":"值。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"final resolutionPresets = ResolutionPreset.values;\nResolutionPreset currentResolutionPreset = ResolutionPreset.high;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"修改方法中的相机控制器实例以使用该变量:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()``currentResolutionPreset","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"final CameraController cameraController = CameraController(\n cameraDescription,\n currentResolutionPreset,\n imageFormatGroup: ImageFormatGroup.jpeg,\n);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"DropdownButton","attrs":{}}],"attrs":{}},{"type":"text","text":"可被定义为如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"DropdownButton(\n dropdownColor: Colors.black87,\n underline: Container(),\n value: currentResolutionPreset,\n items: [\n for (ResolutionPreset preset\n in resolutionPresets)\n DropdownMenuItem(\n child: Text(\n preset\n .toString()\n .split('.')[1]\n .toUpperCase(),\n style:\n TextStyle(color: Colors.white),\n ),\n value: preset,\n )\n ],\n onChanged: (value) {\n setState(() {\n currentResolutionPreset = value!;\n _isCameraInitialized = false;\n });\n onNewCameraSelected(controller!.description);\n },\n hint: Text(\"Select item\"),\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"调用该方法以使用新的清晰度值重新初始化相机控制器。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"录制的图片有点大,大家下载预览吧","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-quality-selector-demo.gif","title":"","type":null},"content":[{"type":"text","text":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-quality-selector-demo.gif","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"变焦控制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用控制器上的方法并传递缩放值来设置相机的缩放级别。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"setZoomLevel()","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在确定缩放级别之前,您应该知道设备相机的最小和最大缩放级别。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义三个变量:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"double _minAvailableZoom = 1.0;\ndouble _maxAvailableZoom = 1.0;\ndouble _currentZoomLevel = 1.0;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"检索这些值的最佳位置是在相机初始化后的方法内部。您可以使用以下方法获得最小和最大缩放级别:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"cameraController\n .getMaxZoomLevel()\n .then((value) => _maxAvailableZoom = value);\n\ncameraController\n .getMinZoomLevel()\n .then((value) => _minAvailableZoom = value);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以实现一个滑块,让用户选择合适的缩放级别;构建的代码","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"Slider","attrs":{}}],"attrs":{}},{"type":"text","text":"如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Row(\n children: [\n Expanded(\n child: Slider(\n value: _currentZoomLevel,\n min: _minAvailableZoom,\n max: _maxAvailableZoom,\n activeColor: Colors.white,\n inactiveColor: Colors.white30,\n onChanged: (value) async {\n setState(() {\n _currentZoomLevel = value;\n });\n await controller!.setZoomLevel(value);\n },\n ),\n ),\n Container(\n decoration: BoxDecoration(\n color: Colors.black87,\n borderRadius: BorderRadius.circular(10.0),\n ),\n child: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Text(\n _currentZoomLevel.toStringAsFixed(1) +\n 'x',\n style: TextStyle(color: Colors.white),\n ),\n ),\n ),\n ],\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每次拖动滑块时,都会调用该方法来更新缩放级别值。在上面的代码中,我们还添加了一个小部件来显示当前的缩放级别值。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"setZoomLevel()``Text","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"录制的图片有点大,大家下载预览吧","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-zoom-demo.gif","title":"","type":null},"content":[{"type":"text","text":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-zoom-demo.gif","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"曝光控制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用控制器上的方法并传递曝光值来设置相机的曝光偏移值。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"setExposureOffset()","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先,让我们检索设备支持的相机曝光的最小值和最大值。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义三个变量:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"ouble _minAvailableExposureOffset = 0.0;\ndouble _maxAvailableExposureOffset = 0.0;\ndouble _currentExposureOffset = 0.0;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"获取方法内的最小和最大相机曝光值:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"cameraController\n .getMinExposureOffset()\n .then((value) => _minAvailableExposureOffset = value);\n\ncameraController\n .getMaxExposureOffset()\n .then((value) => _maxAvailableExposureOffset = value);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们将构建一个用于显示和控制曝光偏移的垂直滑块。Material Design 不提供垂直","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"Slider","attrs":{}}],"attrs":{}},{"type":"text","text":"小部件,但您可以使用四分之三圈的","attrs":{}},{"type":"link","attrs":{"href":"https://api.flutter.dev/flutter/widgets/RotatedBox-class.html","title":null,"type":null},"content":[{"type":"text","text":"RotatedBox类","attrs":{}}]},{"type":"text","text":"来实现这一点。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Container(\n decoration: BoxDecoration(\n color: Colors.white,\n borderRadius: BorderRadius.circular(10.0),\n ),\n child: Padding(\n padding: const EdgeInsets.all(8.0),\n child: Text(\n _currentExposureOffset.toStringAsFixed(1) + 'x',\n style: TextStyle(color: Colors.black),\n ),\n ),\n),\nExpanded(\n child: RotatedBox(\n quarterTurns: 3,\n child: Container(\n height: 30,\n child: Slider(\n value: _currentExposureOffset,\n min: _minAvailableExposureOffset,\n max: _maxAvailableExposureOffset,\n activeColor: Colors.white,\n inactiveColor: Colors.white30,\n onChanged: (value) async {\n setState(() {\n _currentExposureOffset = value;\n });\n await controller!.setExposureOffset(value);\n },\n ),\n ),\n ),\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在上面的代码中,我们","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"Text","attrs":{}}],"attrs":{}},{"type":"text","text":"在滑块顶部构建了一个小部件来显示当前的曝光偏移值。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"录制的图片有点大,大家下载预览吧","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-exposure-offset-demo.gif)","title":"","type":null},"content":[{"type":"text","text":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-exposure-offset-demo.gif)","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"闪光模式选择器","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用该方法并传递一个值来设置相机的闪光模式。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"setFlashMode()``FlashMode","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个变量来存储 flash 模式的当前值:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"FlashMode? _currentFlashMode;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后获取方法内部的初始 flash 模式值:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"_currentFlashMode = controller!.value.flashMode;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在用户界面上,我们将连续显示可用的闪光模式,用户可以点击其中任何一种来选择该闪光模式。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Row(\n mainAxisAlignment: MainAxisAlignment.spaceBetween,\n children: [\n InkWell(\n onTap: () async {\n setState(() {\n _currentFlashMode = FlashMode.off;\n });\n await controller!.setFlashMode(\n FlashMode.off,\n );\n },\n child: Icon(\n Icons.flash_off,\n color: _currentFlashMode == FlashMode.off\n ? Colors.amber\n : Colors.white,\n ),\n ),\n InkWell(\n onTap: () async {\n setState(() {\n _currentFlashMode = FlashMode.auto;\n });\n await controller!.setFlashMode(\n FlashMode.auto,\n );\n },\n child: Icon(\n Icons.flash_auto,\n color: _currentFlashMode == FlashMode.auto\n ? Colors.amber\n : Colors.white,\n ),\n ),\n InkWell(\n onTap: () async {\n setState(() {\n _isCameraInitialized = false;\n });\n onNewCameraSelected(\n cameras[_isRearCameraSelected ? 1 : 0],\n );\n setState(() {\n _isRearCameraSelected = !_isRearCameraSelected;\n });\n },\n child: Icon(\n Icons.flash_on,\n color: _currentFlashMode == FlashMode.always\n ? Colors.amber\n : Colors.white,\n ),\n ),\n InkWell(\n onTap: () async {\n setState(() {\n _currentFlashMode = FlashMode.torch;\n });\n await controller!.setFlashMode(\n FlashMode.torch,\n );\n },\n child: Icon(\n Icons.highlight,\n color: _currentFlashMode == FlashMode.torch\n ? Colors.amber\n : Colors.white,\n ),\n ),\n ],\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"选定的闪光模式将以琥珀色而不是白色突出显示。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/7d/7d2d21f0b941f65a38fc207beeaa3051.gif","alt":"演示相机闪光灯选择器的 gif","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"翻转相机切换","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"要在前后摄像头之间切换,您必须通过向方法提供新值来重新初始化摄像头。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"onNewCameraSelected()","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个布尔变量来了解是否选择了后置摄像头,否则选择了前置摄像头。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"bool _isRearCameraSelected = true;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"以前,我们使用后置摄像头进行初始化,因此我们将存储","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"true","attrs":{}}],"attrs":{}},{"type":"text","text":"在此布尔值中。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"现在,我们将显示一个按钮来在后置摄像头和前置摄像头之间切换:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"InkWell(\n onTap: () {\n setState(() {\n _isCameraInitialized = false;\n });\n onNewCameraSelected(\n cameras[_isRearCameraSelected ? 0 : 1],\n );\n setState(() {\n _isRearCameraSelected = !_isRearCameraSelected;\n });\n },\n child: Stack(\n alignment: Alignment.center,\n children: [\n Icon(\n Icons.circle,\n color: Colors.black38,\n size: 60,\n ),\n Icon(\n _isRearCameraSelected\n ? Icons.camera_front\n : Icons.camera_rear,\n color: Colors.white,\n size: 30,\n ),\n ],\n ),\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在上面的代码中,如果","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_isRearCameraSelected","attrs":{}}],"attrs":{}},{"type":"text","text":"布尔值为","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"true","attrs":{}}],"attrs":{}},{"type":"text","text":",则","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"0","attrs":{}}],"attrs":{}},{"type":"text","text":"作为索引传递给","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"cameras","attrs":{}}],"attrs":{}},{"type":"text","text":"(翻转到前置摄像头),否则","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"1","attrs":{}}],"attrs":{}},{"type":"text","text":"作为索引传递(翻转到后置摄像头)。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"录制的图片有点大,大家下载预览吧","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-exposure-offset-demo.gif","title":"","type":null},"content":[{"type":"text","text":"https://luckly007.oss-cn-beijing.aliyuncs.com/image/camera-exposure-offset-demo.gif","attrs":{}}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"捕捉图像","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以使用相机控制器上的方法使用设备相机拍照。捕获的图片作为a (这是一个跨平台的文件抽象)返回。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"takePicture()``XFile","attrs":{}}],"attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"让我们定义一个函数来处理图片的捕获:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future takePicture() async {\n final CameraController? cameraController = controller;\n if (cameraController!.value.isTakingPicture) {\n // A capture is already pending, do nothing.\n return null;\n }\n try {\n XFile file = await cameraController.takePicture();\n return file;\n } on CameraException catch (e) {\n print('Error occured while taking picture: $e');\n return null;\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"该函数返回捕获的图片,","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"XFile","attrs":{}}],"attrs":{}},{"type":"text","text":"如果捕获成功,则返回","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"null","attrs":{}}],"attrs":{}},{"type":"text","text":"。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"捕获按钮可以定义如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"InkWell(\n onTap: () async {\n XFile? rawImage = await takePicture();\n File imageFile = File(rawImage!.path);\n\n int currentUnix = DateTime.now().millisecondsSinceEpoch;\n final directory = await getApplicationDocumentsDirectory();\n String fileFormat = imageFile.path.split('.').last;\n\n await imageFile.copy(\n '${directory.path}/$currentUnix.$fileFormat',\n );\n },\n child: Stack(\n alignment: Alignment.center,\n children: [\n Icon(Icons.circle, color: Colors.white38, size: 80),\n Icon(Icons.circle, color: Colors.white, size: 65),\n ],\n ),\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"捕获成功后,会将图片保存到应用程序的文档目录中,并以时间戳作为图片名称,以便以后可以轻松访问所有捕获的图片。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"在图像和视频模式之间切换","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"TextButton","attrs":{}}],"attrs":{}},{"type":"text","text":"连续使用两个s 在图像和视频模式之间切换。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个布尔变量来存储所选模式:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"bool _isVideoCameraSelected = false;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"UI 按钮可以这样定义:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Row(\n children: [\n Expanded(\n child: Padding(\n padding: const EdgeInsets.only(\n left: 8.0,\n right: 4.0,\n ),\n child: TextButton(\n onPressed: _isRecordingInProgress\n ? null\n : () {\n if (_isVideoCameraSelected) {\n setState(() {\n _isVideoCameraSelected = false;\n });\n }\n },\n style: TextButton.styleFrom(\n primary: _isVideoCameraSelected\n ? Colors.black54\n : Colors.black,\n backgroundColor: _isVideoCameraSelected\n ? Colors.white30\n : Colors.white,\n ),\n child: Text('IMAGE'),\n ),\n ),\n ),\n Expanded(\n child: Padding(\n padding: const EdgeInsets.only(\n left: 4.0, right: 8.0),\n child: TextButton(\n onPressed: () {\n if (!_isVideoCameraSelected) {\n setState(() {\n _isVideoCameraSelected = true;\n });\n }\n },\n style: TextButton.styleFrom(\n primary: _isVideoCameraSelected\n ? Colors.black\n : Colors.black54,\n backgroundColor: _isVideoCameraSelected\n ? Colors.white\n : Colors.white30,\n ),\n child: Text('VIDEO'),\n ),\n ),\n ),\n ],\n)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e3/e3451909a4fda37058ecf907524b2f47.gif","alt":"演示图像和视频模式的相机切换的 gif","title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"视频录制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"要使用设备摄像头管理视频录制,您必须定义四个函数来处理录制过程的状态:","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"startVideoRecording()","attrs":{}}],"attrs":{}},{"type":"text","text":" 开始视频录制过程","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"stopVideoRecording()","attrs":{}}],"attrs":{}},{"type":"text","text":" 停止视频录制过程","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"pauseVideoRecording()","attrs":{}}],"attrs":{}},{"type":"text","text":" 暂停录制,如果它已经在进行中","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"resumeVideoRecording()","attrs":{}}],"attrs":{}},{"type":"text","text":" 如果处于暂停状态,则恢复录制","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"此外,定义一个布尔变量来存储是否正在进行录制:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"bool _isRecordingInProgress = false;","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"开始录制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以通过调用相机控制器上的方法开始视频录制:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"startVideoRecording()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future startVideoRecording() async {\n final CameraController? cameraController = controller;\n if (controller!.value.isRecordingVideo) {\n // A recording has already started, do nothing.\n return;\n }\n try {\n await cameraController!.startVideoRecording();\n setState(() {\n _isRecordingInProgress = true;\n print(_isRecordingInProgress);\n });\n } on CameraException catch (e) {\n print('Error starting to record video: $e');\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"开始录制后,布尔值","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_isRecordingInProgress","attrs":{}}],"attrs":{}},{"type":"text","text":"设置为","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"true","attrs":{}}],"attrs":{}},{"type":"text","text":"。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"停止录制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以通过调用控制器上的方法来停止已经在进行的视频录制:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"stopVideoRecording()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future stopVideoRecording() async {\n if (!controller!.value.isRecordingVideo) {\n // Recording is already is stopped state\n return null;\n }\n try {\n XFile file = await controller!.stopVideoRecording();\n setState(() {\n _isRecordingInProgress = false;\n print(_isRecordingInProgress);\n });\n return file;\n } on CameraException catch (e) {\n print('Error stopping video recording: $e');\n return null;\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"录制停止后,布尔值","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_isRecordingInProgress","attrs":{}}],"attrs":{}},{"type":"text","text":"设置为","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"false","attrs":{}}],"attrs":{}},{"type":"text","text":"。该方法以格式返回视频文件。","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"stopVideoRecording()``XFile","attrs":{}}],"attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"暂停录制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以通过调用控制器上的方法暂停正在进行的视频录制:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"pauseVideoRecording()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future pauseVideoRecording() async {\n if (!controller!.value.isRecordingVideo) {\n // Video recording is not in progress\n return;\n }\n try {\n await controller!.pauseVideoRecording();\n } on CameraException catch (e) {\n print('Error pausing video recording: $e');\n }\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"恢复录制","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以通过调用控制器上的方法来恢复暂停的视频录制:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"resumeVideoRecording()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future resumeVideoRecording() async {\n if (!controller!.value.isRecordingVideo) {\n // No video recording was in progress\n return;\n }\n try {\n await controller!.resumeVideoRecording();\n } on CameraException catch (e) {\n print('Error resuming video recording: $e');\n }\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"开始和停止录制的按钮","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您可以通过检查","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_isVideoCameraSelected","attrs":{}}],"attrs":{}},{"type":"text","text":"布尔值是否为真并在该位置显示视频开始/停止按钮来修改拍照按钮。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"InkWell(\n onTap: _isVideoCameraSelected\n ? () async {\n if (_isRecordingInProgress) {\n XFile? rawVideo = await stopVideoRecording();\n File videoFile = File(rawVideo!.path);\n\n int currentUnix = DateTime.now().millisecondsSinceEpoch;\n\n final directory = await getApplicationDocumentsDirectory();\n String fileFormat = videoFile.path.split('.').last;\n\n _videoFile = await videoFile.copy(\n '${directory.path}/$currentUnix.$fileFormat',\n );\n\n _startVideoPlayer();\n } else {\n await startVideoRecording();\n }\n }\n : () async {\n // code to handle image clicking\n },\n child: Stack(\n alignment: Alignment.center,\n children: [\n Icon(\n Icons.circle,\n color: _isVideoCameraSelected\n ? Colors.white\n : Colors.white38,\n size: 80,\n ),\n Icon(\n Icons.circle,\n color: _isVideoCameraSelected\n ? Colors.red\n : Colors.white,\n size: 65,\n ),\n _isVideoCameraSelected &&\n _isRecordingInProgress\n ? Icon(\n Icons.stop_rounded,\n color: Colors.white,\n size: 32,\n )\n : Container(),\n ],\n ),\n) ","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"同样,在录制过程中,您可以检查布尔值是否","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_isRecordingInProgress","attrs":{}}],"attrs":{}},{"type":"text","text":"为","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"true","attrs":{}}],"attrs":{}},{"type":"text","text":"并显示暂停/恢复按钮而不是相机翻转按钮。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"上次捕获的预览","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"让我们在相机视图的右下角显示最后拍摄的图片或录制的视频的预览。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为了实现这一点,我们还必须定义一种视频播放方法。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"定义一个视频播放器控制器:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"VideoPlayerController? videoController;","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"以下方法用于使用存储在","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"_videoFile","attrs":{}}],"attrs":{}},{"type":"text","text":"变量中的视频文件启动视频播放器:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Future _startVideoPlayer() async {\n if (_videoFile != null) {\n videoController = VideoPlayerController.file(_videoFile!);\n await videoController!.initialize().then((_) {\n // Ensure the first frame is shown after the video is initialized,\n // even before the play button has been pressed.\n setState(() {});\n });\n await videoController!.setLooping(true);\n await videoController!.play();\n }\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"另外,不要忘记释放方法中的内存:","attrs":{}},{"type":"codeinline","content":[{"type":"text","text":"dispose()","attrs":{}}],"attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"@override\nvoid dispose() {\n // ...\n videoController?.dispose();\n super.dispose();\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"预览的用户界面可以定义如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"Container(\n width: 60,\n height: 60,\n decoration: BoxDecoration(\n color: Colors.black,\n borderRadius: BorderRadius.circular(10.0),\n border: Border.all(color: Colors.white, width: 2),\n image: _imageFile != null\n ? DecorationImage(\n image: FileImage(_imageFile!),\n fit: BoxFit.cover,\n )\n : null,\n ),\n child: videoController != null && videoController!.value.isInitialized\n ? ClipRRect(\n borderRadius: BorderRadius.circular(8.0),\n child: AspectRatio(\n aspectRatio: videoController!.value.aspectRatio,\n child: VideoPlayer(videoController!),\n ),\n )\n : Container(),\n)","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"检索图像/视频文件","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由于我们已将所有捕获的图像和录制的视频存储在应用程序文档目录的单个文件夹中,因此您可以轻松检索所有文件。如果您想在画廊视图中显示它们,或者您只想在预览中显示最后捕获的图像或视频文件的缩略图,这可能是必要的。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们将定义一个方法,当新的捕获或录制完成时,该方法也将刷新预览图像/视频。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"dart"},"content":[{"type":"text","text":"// To store the retrieved files\nList allFileList = [];\n\nrefreshAlreadyCapturedImages() async {\n // Get the directory\n final directory = await getApplicationDocumentsDirectory();\n List fileList = await directory.list().toList();\n allFileList.clear();\n\n List> fileNames = [];\n\n // Searching for all the image and video files using \n // their default format, and storing them\n fileList.forEach((file) {\n if (file.path.contains('.jpg') || file.path.contains('.mp4')) {\n allFileList.add(File(file.path));\n\n String name = file.path.split('/').last.split('.').first;\n fileNames.add({0: int.parse(name), 1: file.path.split('/').last});\n }\n });\n\n // Retrieving the recent file\n if (fileNames.isNotEmpty) {\n final recentFile =\n fileNames.reduce((curr, next) => curr[0] > next[0] ? curr : next);\n String recentFileName = recentFile[1];\n // Checking whether it is an image or a video file\n if (recentFileName.contains('.mp4')) {\n _videoFile = File('${directory.path}/$recentFileName');\n _startVideoPlayer();\n } else {\n _imageFile = File('${directory.path}/$recentFileName');\n }\n\n setState(() {});\n }\n}","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"总结","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"您已经创建了一个具有所有基本功能的成熟相机应用程序。您现在甚至可以向此应用程序添加自定义功能,并自定义用户界面以匹配您应用程序的设计调色板。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章