flutter开发实战-Camera自定义相机拍照功能实现

flutter开发实战-Camera自定义相机拍照功能实现
在这里插入图片描述

一、前言

在项目中使用image_picker插件时候,在android设备上使用无法默认设置前置摄像头(暂时不清楚什么原因),由于项目默认需要使用前置摄像头,所以最终采用自定义相机实现拍照功能。

二、Camera使用前设置

在工程的iOS的info.plist文件中添加相机、麦克风权限描述

<key>NSCameraUsageDescription</key>
<string>your usage description here</string>
<key>NSMicrophoneUsageDescription</key>
<string>your usage description here</string>
    

在工程的Android的gradle设置minSdkVersion

找到android/app/build.gradle文件

minSdkVersion 21
    

二、使用插件Camera插件

camera : 适用于iOS、Android和Web的Flutter插件,允许访问设备摄像头。

我们需要在工程中引入camera插件

pubspec.yaml中引入插件

  # Camera相机拍照等
  camera: ^0.10.5+5
    

处理相机访问权限

在初始化相机控制器时可能会引发权限错误,需要处理这些错误。

  • CameraAccessDenied:当用户拒绝相机访问权限时抛出。

  • CameraAccessDeniedWithoutPrompt:仅限iOS。当用户先前拒绝该权限时抛出。iOS不允许再次提示警报对话框。用户必须进入“设置”>“隐私”>“相机”才能访问相机。

  • CameraAccessRestricted:仅限iOS。当摄像头访问受到限制且用户无法授予权限(家长控制)时抛出。

  • AudioAccessDenied:当用户拒绝音频访问权限时抛出。

  • AudioAccessDeniedWithoutPrompt:目前仅限iOS。当用户先前拒绝该权限时抛出。iOS不允许再次提示警报对话框。用户必须转到“设置”>“隐私”>“麦克风”才能启用音频访问。

  • AudioAccessRestricted:目前仅限iOS。当音频访问受到限制并且用户无法授予权限(家长控制)时抛出。

2.1、camera功能设置

当使用camera时,我们需要设置一些camera的属性内容,比如切换前后摄像头、开启拍照、开启预览、停止预览等。

获取cameras

final cameras = await availableCameras();

camera中使用CameraController来控制相关功能。

设置缩放级别zoomLevel

Future<void> setZoomLevel(double scale) async {
    await controller!.setZoomLevel(scale);
  }
    

切换闪光灯模式

  void onSetFlashModeButtonPressed(FlashMode mode) {
    setFlashMode(mode).then((_) {
      if (mounted) {
        setState(() {});
      }
      showInSnackBar('Flash mode set to ${mode.toString().split('.').last}');
    });
  }
    

设置曝光模式

  void onSetExposureModeButtonPressed(ExposureMode mode) {
    setExposureMode(mode).then((_) {
      if (mounted) {
        setState(() {});
      }
      showInSnackBar('Exposure mode set to ${mode.toString().split('.').last}');
    });
  }
    

设置焦距模式

  void onSetFocusModeButtonPressed(FocusMode mode) {
    setFocusMode(mode).then((_) {
      if (mounted) {
        setState(() {});
      }
      showInSnackBar('Focus mode set to ${mode.toString().split('.').last}');
    });
  }
    

开启预览

  Future<void> onResumePreview() async {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return;
    }

    if (cameraController.value.isPreviewPaused) {
      await cameraController.resumePreview();
    }
  }
    

暂停预览

  Future<void> onPausePreview() async {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return;
    }

    if (!cameraController.value.isPreviewPaused) {
      await cameraController.pausePreview();
    }
  }
    

切换前后摄像头

void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) {
    if (controller == null) {
      return;
    }

    final CameraController? cameraController = controller;

    final Offset offset = Offset(
      details.localPosition.dx / constraints.maxWidth,
      details.localPosition.dy / constraints.maxHeight,
    );
    cameraController?.setExposurePoint(offset);
    cameraController?.setFocusPoint(offset);
  }

  Future<void> onNewCameraSelected(CameraDescription cameraDescription) async {
    final CameraController cameraController = CameraController(
      cameraDescription,
      ResolutionPreset.high,
      enableAudio: enableAudio,
      imageFormatGroup: ImageFormatGroup.jpeg,
    );

    controller = cameraController;

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

    try {
      await cameraController.initialize();
      await Future.wait(<Future<Object>>[
        // The exposure mode is currently not supported on the web.
        cameraController
            .getMaxZoomLevel()
            .then((double value) => _maxAvailableZoom = value),
        cameraController
            .getMinZoomLevel()
            .then((double value) => _minAvailableZoom = value),
      ]);
    } on CameraException catch (e) {
      // _showCameraException(e);
    }

    setState(() {
      isCameraStarting = true;
    });
    controller!.initialize().then((_) {
      if (!mounted) {
        return;
      }

      setState(() {
        isCameraStarting = false;
      });
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // Handle access errors here.
            break;
          default:
            // Handle other errors here.
            break;
        }
      }
    });

    if (mounted) {
      setState(() {});
    }
  }
    

上面介绍了一些CameraController的常用设置,当然肯定不全,大致列了几条。

2.2、WidgetsBinding 生命周期改变相机设置

我们自定义Camera,需要在didChangeAppLifecycleState来处理相机。我们需要添加mixin WidgetsBindingObserver

在initState中添加WidgetsBinding.instance?.addObserver(this);

在dispose中移除WidgetsBinding.instance?.removeObserver(this);

这样我们就可以在app的生命周期状态改变时候,更新相机

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final CameraController? cameraController = controller;

    // App state changed before we got the chance to initialize.
    if (cameraController == null || !cameraController.value.isInitialized) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      cameraController.dispose();
    } else if (state == AppLifecycleState.resumed) {
      onNewCameraSelected(cameraController.description);
    }
  }
    

2.3、处理预览的画面出现变形的问题

在处理自定义相机功能,我们需要处理预览的画面出现变形的问题。这里我们需要使用CameraPreview。
我们需要使用Transform.scale来进行处理,处理预览的画面出现变形的问题的解决代码如下

Widget buildCameraPreviewWidget(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final CameraController? cameraController = controller;

    return Container(
      width: size.width,
      height: size.height,
      child: Stack(
        alignment: Alignment.center,
        clipBehavior: Clip.hardEdge,
        children: [
          RepaintBoundary(
            key: _cameraViewGlobalKey,
            child: Transform.scale(
              scale: 1.0,
              // scale: controller!.value.aspectRatio / deviceRatio,
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: size.aspectRatio,
                child: OverflowBox(
                  alignment: Alignment.center,
                  child: FittedBox(
                    fit: BoxFit.fitHeight,
                    child: SizedBox(
                      width: size.width,
                      height: size.width * cameraController!.value.aspectRatio,
                      child: Stack(fit: StackFit.expand, children: <Widget>[
                        _cameraPreviewWidget(),
                      ]),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Display the preview from the camera (or a message if the preview is not available).
  Widget _cameraPreviewWidget() {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      return const Text(
        'cameraController未初始化完成',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return Listener(
        onPointerDown: (_) => _pointers++,
        onPointerUp: (_) => _pointers--,
        child: CameraPreview(
          controller!,
          child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
            return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onScaleStart: _handleScaleStart,
              onScaleUpdate: _handleScaleUpdate,
              onTapDown: (TapDownDetails details) =>
                  onViewFinderTap(details, constraints),
            );
          }),
        ),
      );
    }
  }
    

在代码中,我们使用Transform.scale设置为1.0,当设置AspectRatio来设置size.aspectRatio。

2.4、实现拍照功能

在我们代码中,我们使用takePicture来实现拍照,拍照代码如下

Future<void> onTakePicture() async {
    setState(() {
      isTaking = true;
    });

    takePicture().then((XFile? file) async {
      if (mounted) {
        onPausePreview();
        if (file != null) {
          // 保存到相册
          // await SaveToAlbumUtil.saveLocalImage(file.path);
          RenderBox renderBox = _cameraContainerGlobalKey.currentContext!
              .findRenderObject() as RenderBox;
          // offset.dx , offset.dy 就是控件的左上角坐标
          Offset offset = renderBox.localToGlobal(Offset.zero);
          //获取size
          Size size = renderBox.size;

          // 创建文件path
          String imageDir = await PathUtil.createDirectory("local_images");
          String imagePath = '$imageDir/${TimeUtil.currentTimeMillis()}.png';

          // // 获取当前设备的像素比
          double dpr = ui.window.devicePixelRatio;
          print("devicePixelRatio:${dpr}");
          print(
              "offset:(${offset.dx},${offset.dy})--size:(${size.width},${size.height})");

          File? targetFile = await ImageUtil.cropImage(
            file.path,
            imagePath,
            x: (dpr * offset.dx).floor(),
            y: (dpr * offset.dy).floor(),
            width: (dpr * size.width).ceil(),
            height: (dpr * size.height).ceil(),
            flipHorizontal: isCameraFront,
          );
          print("cropImage targetFile:${targetFile}");
          if (targetFile != null) {
            selectedImagePath = targetFile.path;
            // await SaveToAlbumUtil.saveLocalImage(targetFile.path);
          }
          setState(() {
            isHasTakePhoto = true;
          });
        } else {
          // 没有获得图片,重试
        }
        setState(() {
          isTaking = false;
        });
      }
    });
  }
    

在裁剪图片中实现如下

import 'dart:io';
import 'dart:math';
import 'dart:ui' as ui;
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:image/image.dart' as IMG;

class ImageUtil {
  //拿到图片的字节数组
  static Future<ui.Image> loadImageByFile(String path) async {
    var list = await File(path).readAsBytes();
    return ImageUtil.loadImageByUInt8List(list);
  }

  //通过[Uint8List]获取图片
  static Future<ui.Image> loadImageByUInt8List(Uint8List list) async {
    ui.Codec codec = await ui.instantiateImageCodec(list);
    ui.FrameInfo frame = await codec.getNextFrame();
    return frame.image;
  }

  // 根据GlobalKey来截图Widget
  static Future<Uint8List?> makeImageUInt8List(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
    // 这个可以获取当前设备的像素比
    var dpr = ui.window.devicePixelRatio;
    ui.Image image = await boundary.toImage(pixelRatio: dpr);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List? pngBytes = byteData?.buffer.asUint8List();
    return pngBytes;
  }

  static Future<File?> cropSquare(
      String srcFilePath, String destFilePath, bool flip) async {
    var bytes = await File(srcFilePath).readAsBytes();
    IMG.Image? src = IMG.decodeImage(bytes);

    if (src != null) {
      var cropSize = min(src.width, src.height);
      int offsetX = (src.width - min(src.width, src.height)) ~/ 2;
      int offsetY = (src.height - min(src.width, src.height)) ~/ 2;

      // IMG.Image destImage = IMG.copyCrop(src, offsetX, offsetY, cropSize, cropSize);
      IMG.Image destImage = IMG.copyCrop(src,
          x: offsetX, y: offsetY, width: cropSize, height: cropSize);

      if (flip) {
        destImage = IMG.flipVertical(destImage);
      }

      var jpg = IMG.encodeJpg(destImage);
      return await File(destFilePath).writeAsBytes(jpg);
    } else {
      throw StateError("cropSquare error");
    }
  }

  static Future<File?> cropImage(
    String srcFilePath,
    String destFilePath, {
    required int x,
    required int y,
    required int width,
    required int height,
    bool flipVertical = false,
    bool flipHorizontal = false,
  }) async {
    var bytes = await File(srcFilePath).readAsBytes();
    IMG.Image? src = IMG.decodeImage(bytes);

    if (src != null) {
      print("cropImage scr size:(${src.width},${src.height})");
      IMG.Image destImage = IMG.copyCrop(src,
          x: x, y: y, width: width, height: height);

      if (flipVertical) {
        destImage = IMG.flipVertical(destImage);
      }

      if (flipHorizontal) {
        destImage = IMG.flipHorizontal(destImage);
      }

      var jpg = IMG.encodeJpg(destImage);
      return await File(destFilePath).writeAsBytes(jpg);
    } else {
      throw StateError("cropSquare error");
    }
  }
}

    

2.5、拍照完重拍逻辑

当拍照后可能需要重新拍照,这时候我们需要重拍逻辑。

void onRetakeButtonPressed() {
    setState(() {
      isHasTakePhoto = false;
    });
    selectedImagePath = null;
    onResumePreview();
  }

Future<void> onResumePreview() async {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return;
    }

    if (cameraController.value.isPreviewPaused) {
      await cameraController.resumePreview();
    }
  }

    

三、实现自定义相机拍照的功能完整代码

我们实现了实现自定义相机拍照的功能完整代码如下

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_demolab/image_util.dart';
import 'package:flutter_app_demolab/path_util.dart';
import 'dart:ui' as ui;

import 'package:flutter_app_demolab/tools/utils/color_util.dart';
import 'package:flutter_app_demolab/tools/utils/time_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MyCameraPage extends StatefulWidget {
  const MyCameraPage({
    super.key,
    required this.cameras,
    required this.onSelectedImagePathPressed,
  });

  final List<CameraDescription> cameras;
  final Function(String? selectedImagePath) onSelectedImagePathPressed;

  @override
  State<MyCameraPage> createState() => _MyCameraPageState();
}

class _MyCameraPageState extends State<MyCameraPage>
    with WidgetsBindingObserver, TickerProviderStateMixin {
  CameraController? controller;
  GlobalKey _cameraViewGlobalKey = GlobalKey();
  GlobalKey _cameraContainerGlobalKey = GlobalKey();

  bool enableAudio = false;

  // Counting pointers (number of user fingers on screen)
  ///以下是关于手指缩放画面的变量
  int _pointers = 0;
  double _minAvailableZoom = 1.0;
  double _maxAvailableZoom = 1.0;
  double _currentScale = 1.0;
  double _baseScale = 1.0;

  Size? mediaSize;
  double? scale;
  double? defaultZoomLevel;

  bool isHasTakePhoto = false;
  bool isCameraFront = true;
  String? selectedImagePath;
  bool isTaking = false;
  bool isCameraStarting = false;

  @override
  void initState() {
    super.initState();
    // To display the current output from the Camera,
    // create a CameraController.
    if (widget.cameras.isNotEmpty && widget.cameras.length >= 2) {
      controller = CameraController(
        // Get a specific camera from the list of available cameras.
        widget.cameras[1],
        // Define the resolution to use.
        ResolutionPreset.high,
      );

      // Next, initialize the controller. This returns a Future.
      setState(() {
        isCameraStarting = true;
      });
      controller!.initialize().then((_) {
        if (!mounted) {
          return;
        }

        setState(() {
          isCameraStarting = false;
        });
      }).catchError((Object e) {
        if (e is CameraException) {
          switch (e.code) {
            case 'CameraAccessDenied':
              // Handle access errors here.
              break;
            default:
              // Handle other errors here.
              break;
          }
        }
      });
    }

    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    controller?.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final CameraController? cameraController = controller;

    // App state changed before we got the chance to initialize.
    if (cameraController == null || !cameraController.value.isInitialized) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      cameraController.dispose();
    } else if (state == AppLifecycleState.resumed) {
      onNewCameraSelected(cameraController.description);
    }
  }

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: buildCameraContainer(context),
    );
  }

  Widget buildCameraContainer(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    if (widget.cameras.isEmpty) {
      return Container(
        width: size.width,
        height: size.height,
        decoration: const BoxDecoration(
          color: Colors.black,
        ),
        child: Text(
          "未获取到可用的相机,请退出重试。",
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          softWrap: true,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            fontStyle: FontStyle.normal,
            color: ColorUtil.hexColor(0xffffff),
            decoration: TextDecoration.none,
          ),
        ),
      );
    } else {
      return Container(
        key: _cameraContainerGlobalKey,
        width: size.width,
        height: size.height,
        decoration: const BoxDecoration(
          color: Colors.black,
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Column(
              children: [
                Expanded(
                  child: buildFutureBuilder(context),
                )
              ],
            ),
            buildStackBarWidget(context),
          ],
        ),
      );
    }
  }

  Widget buildFutureBuilder(BuildContext context) {
    if (controller != null && controller!.value.isInitialized) {
      ///初始化完成以后,再获取可以缩放画面最大最小的参数
      mediaSize = MediaQuery.of(context).size;
      scale = 1 / (controller!.value.aspectRatio * mediaSize!.aspectRatio);
      controller!
          .getMaxZoomLevel()
          .then((double value) => _maxAvailableZoom = value);
      controller!
          .getMinZoomLevel()
          .then((double value) => _minAvailableZoom = value);
      return buildCameraPreviewWidget(context);
    }
    return const Center(child: CircularProgressIndicator());
  }

  Widget buildStackBarWidget(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    double bottomBarHeight = 120;
    double cameraHeight = size.height - bottomBarHeight;
    EdgeInsets viewPadding = MediaQuery.of(context).viewPadding;
    return Container(
      child: Stack(
        children: [
          Positioned(
            bottom: 0,
            child: Container(
              width: size.width,
              height: bottomBarHeight,
              color: Colors.transparent,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Positioned(
                    left: 25,
                    child: buildCloseIcon(context),
                  ),
                  buildTakePhotoButton(context),
                  Positioned(
                    right: 25,
                    child: buildRetakeButton(context),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            top: viewPadding.top + 25,
            right: 10,
            child: buildExchangeButton(context),
          ),
        ],
      ),
    );
  }

  Widget buildCameraPreviewWidget(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final CameraController? cameraController = controller;

    return Container(
      width: size.width,
      height: size.height,
      child: Stack(
        alignment: Alignment.center,
        clipBehavior: Clip.hardEdge,
        children: [
          RepaintBoundary(
            key: _cameraViewGlobalKey,
            child: Transform.scale(
              scale: 1.0,
              // scale: controller!.value.aspectRatio / deviceRatio,
              alignment: Alignment.center,
              child: AspectRatio(
                aspectRatio: size.aspectRatio,
                child: OverflowBox(
                  alignment: Alignment.center,
                  child: FittedBox(
                    fit: BoxFit.fitHeight,
                    child: SizedBox(
                      width: size.width,
                      height: size.width * cameraController!.value.aspectRatio,
                      child: Stack(fit: StackFit.expand, children: <Widget>[
                        _cameraPreviewWidget(),
                      ]),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Display the preview from the camera (or a message if the preview is not available).
  Widget _cameraPreviewWidget() {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      return const Text(
        'cameraController未初始化完成',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return Listener(
        onPointerDown: (_) => _pointers++,
        onPointerUp: (_) => _pointers--,
        child: CameraPreview(
          controller!,
          child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
            return GestureDetector(
              behavior: HitTestBehavior.opaque,
              onScaleStart: _handleScaleStart,
              onScaleUpdate: _handleScaleUpdate,
              onTapDown: (TapDownDetails details) =>
                  onViewFinderTap(details, constraints),
            );
          }),
        ),
      );
    }
  }

  Widget buildCloseIcon(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
      },
      child: Container(
        color: Colors.transparent,
        child: Container(
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            color: Colors.transparent,
            border: Border.all(
              color: Colors.transparent,
              style: BorderStyle.solid,
              width: 1,
            ),
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          child: Icon(
            Icons.close,
            size: 30,
            color: Colors.white,
            weight: 0.5,
          ),
        ),
      ),
    );
  }

  Widget buildTakePhotoButton(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (isTaking == false) {
          if (isHasTakePhoto == true) {
            widget.onSelectedImagePathPressed(selectedImagePath);
            Navigator.pop(context);
          } else {
            onTakePicturePressed();
          }
        }
      },
      child: Container(
        color: Colors.transparent,
        child: Container(
          width: 60,
          height: 60,
          decoration: const BoxDecoration(
            color: Colors.transparent,
          ),
          child: Stack(
            alignment: Alignment.center,
            children: [
              Image.asset(
                "assets/camera/my_take_photo.png",
                width: 60.0,
                height: 60.0,
                fit: BoxFit.contain,
              ),
              buildHasCheck(context),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildHasCheck(BuildContext context) {
    if (isTaking == true) {
      return buildLoading(context);
    }
    if (isHasTakePhoto) {
      return Icon(
        Icons.check,
        size: 30,
        color: Colors.black,
        weight: 0.5,
      );
    }
    return Container();
  }

  Widget buildExchangeButton(BuildContext context) {
    if (isHasTakePhoto == true) {
      return Container();
    }
    return GestureDetector(
      onTap: () {
        onExchangeCameraPressed();
      },
      child: Container(
        color: Colors.transparent,
        child: Container(
          width: 50,
          height: 50,
          decoration: BoxDecoration(
            color: Colors.transparent,
            border: Border.all(
              color: Colors.transparent,
              style: BorderStyle.solid,
              width: 2,
            ),
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          child: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Colors.transparent,
              border: Border.all(
                color: Colors.transparent,
                style: BorderStyle.solid,
                width: 5,
              ),
              borderRadius: BorderRadius.all(Radius.circular(20)),
            ),
            child: Image.asset(
              "assets/camera/my_exchange_camera.png",
              width: 50.0,
              height: 50.0,
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
    );
  }

  Widget buildRetakeButton(BuildContext context) {
    if (isHasTakePhoto == false) {
      return Container();
    }

    return GestureDetector(
      onTap: () {
        onRetakeButtonPressed();
      },
      child: Container(
        color: Colors.transparent,
        child: Container(
          width: 70,
          height: 38,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: ColorUtil.hexColor(0x000000, alpha: 0.25),
            border: Border.all(
              color: Colors.transparent,
              style: BorderStyle.solid,
              width: 2,
            ),
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          child: Text(
            "重拍",
            textAlign: TextAlign.center,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            softWrap: true,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              fontStyle: FontStyle.normal,
              color: ColorUtil.hexColor(0xffffff),
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ),
    );
  }

  Widget buildLoading(BuildContext context) {
    return SizedBox(
      height: 58,
      width: 58,
      child: CircularProgressIndicator(
        backgroundColor: Colors.grey[200],
        valueColor: AlwaysStoppedAnimation(Colors.blue),
      ),
    );
  }

  void onRetakeButtonPressed() {
    setState(() {
      isHasTakePhoto = false;
    });
    selectedImagePath = null;
    onResumePreview();
  }

  Future<void> onPausePreview() async {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return;
    }

    if (!cameraController.value.isPreviewPaused) {
      await cameraController.pausePreview();
    }
  }

  Future<void> onResumePreview() async {
    final CameraController? cameraController = controller;

    if (cameraController == null || !cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return;
    }

    if (cameraController.value.isPreviewPaused) {
      await cameraController.resumePreview();
    }
  }

  Future<void> onExchangeCameraPressed() async {
    setState(() {
      isHasTakePhoto = false;
    });
    if (isCameraFront == true) {
      if (widget.cameras.isNotEmpty && widget.cameras.length >= 2) {
        onNewCameraSelected(widget.cameras[0]);
      }
      isCameraFront = false;
    } else {
      if (widget.cameras.isNotEmpty && widget.cameras.length >= 2) {
        onNewCameraSelected(widget.cameras[1]);
      }
      isCameraFront = true;
    }
  }

  void onTakePicturePressed() {
    onTakePicture();
  }

  Future<void> onTakePicture() async {
    setState(() {
      isTaking = true;
    });

    takePicture().then((XFile? file) async {
      if (mounted) {
        onPausePreview();
        if (file != null) {
          // 保存到相册
          // await SaveToAlbumUtil.saveLocalImage(file.path);
          RenderBox renderBox = _cameraContainerGlobalKey.currentContext!
              .findRenderObject() as RenderBox;
          // offset.dx , offset.dy 就是控件的左上角坐标
          Offset offset = renderBox.localToGlobal(Offset.zero);
          //获取size
          Size size = renderBox.size;

          // 创建文件path
          String imageDir = await PathUtil.createDirectory("local_images");
          String imagePath = '$imageDir/${TimeUtil.currentTimeMillis()}.png';

          // // 获取当前设备的像素比
          double dpr = ui.window.devicePixelRatio;
          print("devicePixelRatio:${dpr}");
          print(
              "offset:(${offset.dx},${offset.dy})--size:(${size.width},${size.height})");

          File? targetFile = await ImageUtil.cropImage(
            file.path,
            imagePath,
            x: (dpr * offset.dx).floor(),
            y: (dpr * offset.dy).floor(),
            width: (dpr * size.width).ceil(),
            height: (dpr * size.height).ceil(),
            flipHorizontal: isCameraFront,
          );
          print("cropImage targetFile:${targetFile}");
          if (targetFile != null) {
            selectedImagePath = targetFile.path;
            // await SaveToAlbumUtil.saveLocalImage(targetFile.path);
          }
          setState(() {
            isHasTakePhoto = true;
          });
        } else {
          // 没有获得图片,重试
        }
        setState(() {
          isTaking = false;
        });
      }
    });
  }

  Future<void> _handleScaleStart(ScaleStartDetails details) async {
    _baseScale = _currentScale;
    await controller!.setZoomLevel(_minAvailableZoom);
  }

  Future<void> _handleScaleUpdate(ScaleUpdateDetails details) async {
    // When there are not exactly two fingers on screen don't scale
    if (controller == null || _pointers != 2) {
      return;
    }

    _currentScale = (_baseScale * details.scale)
        .clamp(_minAvailableZoom, _maxAvailableZoom);

    await controller!.setZoomLevel(_currentScale);
  }

  void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) {
    if (controller == null) {
      return;
    }

    final CameraController? cameraController = controller;

    final Offset offset = Offset(
      details.localPosition.dx / constraints.maxWidth,
      details.localPosition.dy / constraints.maxHeight,
    );
    cameraController?.setExposurePoint(offset);
    cameraController?.setFocusPoint(offset);
  }

  Future<void> onNewCameraSelected(CameraDescription cameraDescription) async {
    final CameraController cameraController = CameraController(
      cameraDescription,
      ResolutionPreset.high,
      enableAudio: enableAudio,
      imageFormatGroup: ImageFormatGroup.jpeg,
    );

    controller = cameraController;

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

    try {
      await cameraController.initialize();
      await Future.wait(<Future<Object>>[
        // The exposure mode is currently not supported on the web.
        cameraController
            .getMaxZoomLevel()
            .then((double value) => _maxAvailableZoom = value),
        cameraController
            .getMinZoomLevel()
            .then((double value) => _minAvailableZoom = value),
      ]);
    } on CameraException catch (e) {
      // _showCameraException(e);
    }

    setState(() {
      isCameraStarting = true;
    });
    controller!.initialize().then((_) {
      if (!mounted) {
        return;
      }

      setState(() {
        isCameraStarting = false;
      });
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // Handle access errors here.
            break;
          default:
            // Handle other errors here.
            break;
        }
      }
    });

    if (mounted) {
      setState(() {});
    }
  }

  Future<XFile?> takePicture() async {
    final CameraController? cameraController = controller;
    if (cameraController == null || !cameraController.value.isInitialized) {
      print("Error: select a camera first.");
      return null;
    }

    if (cameraController.value.isTakingPicture) {
      // A capture is already pending, do nothing.
      return null;
    }

    try {
      final XFile file = await cameraController.takePicture();
      return file;
    } on CameraException catch (e) {
      print("takePicture CameraException e:${e.toString()}");
      return null;
    }
  }
}
    

当需要拍照时候,我们调用showModalBottomSheet来打开camera


//显示底部弹窗
  static void bottomSheetDialog(BuildContext context, Widget widget) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return widget;
      },
    );
  }

  //返回上一级
  static void pop(BuildContext context) {
    Navigator.pop(context);
  }

    

打开自定义相机页面


Future<void> testCustomCamera(BuildContext context) async {
    final cameras = await availableCameras();
    DialogUtils.bottomSheetDialog(
      context,
      MyCameraPage(
        cameras: cameras,
        onSelectedImagePathPressed: (String? selectedImagePath) {
          print("selectedImageFilePath:${selectedImagePath}");
          if (selectedImagePath != null) {
            // File imageFile = File(selectedImagePath!);
            // if (callback != null) {
            //   callback(imageFile);
            // }
          }
        },
      ),
    );
  }

    

https://brucegwo.blog.csdn.net/article/details/135997096

四、小结

flutter开发实战-Camera自定义相机拍照功能实现

学习记录,每天不停进步。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/367437.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

机器学习 | 如何构建自己的决策树算法?

决策树思想的来源非常朴素&#xff0c;程序设计中的条件分支结构就是if-else结构&#xff0c;最早的决策树就是利用这类结构分割数据的一种分类学习方法 目录 初识决策树 决策树原理 cart剪枝 特征提取 泰坦尼克号乘客生存预测(实操) 回归决策树 初识决策树 决策树是一种…

分布式事务 seata+nacos 部署

分布式事务 seatanacos 部署 一、下载seata二、解压配置三、导入数据库四、nacos配置五、配置要引入事务的模块的配置文件六、启动七、测试 这里使用的版本&#xff1a; nacos&#xff1a;2.0.4 seata&#xff1a;1.5.2 seata官方地址&#xff1a;https://seata.apache.org/zh-…

【数据结构】并查集(路径压缩)

文章目录 并查集1.朴素版本2.路径压缩3.按秩合并4.启发式合并5.练习题 并查集 1.朴素版本 1. 并查集解决的是连通块的问题&#xff0c;常见操作有&#xff0c;判断两个元素是否在同一个连通块当中&#xff0c;两个非同一连通块的元素合并到一个连通块当中。 并查集和堆的结构…

零基础学Python(6)— 运算符

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。运算符是一种用于执行特定操作的符号或关键字。在编程中&#xff0c;运算符用于对变量、常量和表达式进行操作&#xff0c;以产生一个结果。下面将详细介绍Python语言中常见的运算符&#xff01;~&#x1f308; 目录 &a…

Three.js学习2:页面引入 Three.js

一、关于 Three.js 的版本 随着页面3D化应用越来越多&#xff0c;近两年 Three.js 处于飞速发展之中。现在 Three.js 几乎每个月都会发布一个新的版本&#xff0c;会增加新的 API&#xff0c;废掉一些旧的功能之类的。 可以从 Three.js 官网 Three.js – JavaScript 3D Libra…

【Linux】线程安全——同步和互斥

需要云服务器等云产品来学习Linux的同学可以移步/–>腾讯云<–/官网&#xff0c;轻量型云服务器低至112元/年&#xff0c;优惠多多。&#xff08;联系我有折扣哦&#xff09; 文章目录 引入1. Linux线程互斥1.1 互斥的相关概念1.2 互斥量mutex1.3 mutex的使用1.4 mutex的…

Windows11 用 HyperV 安装 Ubuntu-16.04 虚拟机

Windows11 用 HyperV 安装 Ubuntu-16.04 虚拟机 1. 确保已经开启HyperV2. 准备Ubuntu16.04镜像&#xff08;推荐64位的&#xff09;3. HyperV ->快速创建 -> 更改安装源 选刚刚下载的镜像&#xff08;.iso&#xff09;文件就好 -> 创建虚拟机[^1] 前提&#xff1a;VMw…

<网络安全>《15 移动安全管理系统》

1 概念 移动安全管理系统&#xff0c;MSM&#xff0c;Mobile security management,提供大而全的功能解决方案&#xff0c;覆盖了企业移动信息化中所涉及到安全沙箱、数据落地保护、威胁防护、设备管理、应用管理、文档管理、身份认证等各个维度。移动安全管理系统将设备管理和…

基于SpringBoot Vue单位考勤管理系统

大家好✌&#xff01;我是Dwzun。很高兴你能来阅读我&#xff0c;我会陆续更新Java后端、前端、数据库、项目案例等相关知识点总结&#xff0c;还为大家分享优质的实战项目&#xff0c;本人在Java项目开发领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目&#x…

MacOS安装JDK+Maven+Idea插件+nvm等

Java安装环境(MacOS)JDKMavenIdea插件nvm等 背景&#xff1a;新机安装开发环境发现需要找很多文章&#xff0c;&#xff0c;&#xff0c;&#xff0c;这里一篇文章安装所有环境 文章目录 Java安装环境(MacOS)JDKMavenIdea插件nvm等一、安装JDK①&#xff1a;下载②&#xff1a;…

opencv0014 索贝尔(sobel)算子

前面学习的滤波器主要是用来模糊图像&#xff0c;今天一起来了解关于边缘识别的滤波吧&#xff01;嘿嘿 边缘 边缘是像素值发生跃迁的位置&#xff0c;是图像的显著特征之一&#xff0c;在图像特征提取&#xff0c;对象检测&#xff0c;模式识别等方面都有重要的作用。 人眼如…

【牛B得一塌糊涂】窗口归一化技术,改进医学图像的分布外泛化能力

窗口归一化技术&#xff0c;改进医学图像的分布外泛化能力 提出背景WIN、WIN-WIN、无参数归一化、特征级别数据增强如何提升分布外的泛化&#xff1f; 总结子问题1: 医学图像中的局部特征表示不足子问题2: 训练数据与新场景数据分布不一致子问题3: 模型在分布外数据上泛化能力不…

docker 容器指定主机网段

docker 容器指定主机网段。 直接连接到物理网络&#xff1a;使用macvlan技术可以让Docker容器直接连接到物理网络&#xff0c;而不需要通过NAT或端口映射的方式来访问它们。可以提高网络性能和稳定性&#xff0c;同时也可以使容器更加透明和易于管理。 1、查询网卡的名称&…

C++初阶之类与对象(上)详细解析

个人主页&#xff1a;点我进入主页 专栏分类&#xff1a;C语言初阶 C语言进阶 数据结构初阶 Linux C初阶 欢迎大家点赞&#xff0c;评论&#xff0c;收藏。 一起努力&#xff0c;一起奔赴大厂 目录 一.前言 二.类的定义和使用 2.1类的引入 2.2类的定义和访问限定…

ubuntu22.04安装部署02:禁用显卡更新

一、查看可用显卡驱动 ubuntu-drivers devices 二、查看显卡信息 # -i表示不区分大小写 lspci | grep -i nvidia nvidia-smi 三、查看已安装显卡驱动 cat /proc/driver/nvidia/version 四、锁定显卡升级 使用cuda自带额显卡驱动&#xff0c;居然无法&#xff0c;找到如何锁…

构建LLM辅助生物威胁制造预警系统 人类越发展获取的超能力越大,破坏力越大,威胁越大。我们需要什么样的预警系统?既克服威胁又具有超能力 安全基础

https://openai.com/research/building-an-early-warning-system-for-llm-aided-biological-threat-creation 人类越发展获取的超能力越大&#xff0c;破坏力就越大&#xff0c;威胁越大。 人工智能就是为了赋予人人都能有超能力&#xff0c;而一旦被恶意或无意使用又威胁到人…

KNIME 节点之战(Game of Nodes)锦标赛

“Hark! I summon thee to a contest of nodes. Art thou endowed with the courage for the encounter?” “听着&#xff01;我在此邀请你加入一场节点之战。你有勇气面对吗&#xff1f;” 官方链接 活动概要与参赛守则 诚邀您加入 KNIME 节点之战 —— 首届全球工作流挑战大…

Megatron-LM源码系列(七):Distributed-Optimizer分布式优化器实现Part2

1. 使用入口 DistributedOptimizer类定义在megatron/optimizer/distrib_optimizer.py文件中。创建的入口是在megatron/optimizer/__init__.py文件中的get_megatron_optimizer函数中。根据传入的args.use_distributed_optimizer参数来判断是用DistributedOptimizer还是Float16O…

【C++初阶】--入门基础(二)

目录 一.C输出与输入 二.缺省参数 1.概念 2.缺省参数分类 (1) 全缺省参数 (2)半缺省参数 三.函数重载 1.概念 2.C支持函数重载的原理--名字修饰 四.引用 1.概念 2.语法 3.引用的特性 (1)引用在定义时必须初始化 (2)引用时不能改变指向 (3)一个变量…

区间时间检索

前端 <el-col :md"6" v-if"advanced"><el-form-item :label"$t(inRecord.column.createTime)"><el-date-pickerstyle"width: 100%;"v-model"daterangeCreateTime"value-format"yyyy-MM-dd"type&qu…