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

news2024/7/4 4:35:39

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自定义相机拍照功能实现

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

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

完整的 HTTP 请求所经历的步骤及分布式事务解决方案

1. 对分布式事务的了解 分布式事务是企业集成中的一个技术难点&#xff0c;也是每一个分布式系统架构中都会涉及到的一个东西&#xff0c; 特别是在微服务架构中&#xff0c;几乎可以说是无法避免。 首先要搞清楚&#xff1a;ACID、CAP、BASE理论。 ACID 指数据库事务正确执行…

【Java程序设计】【C00207】基于(JavaWeb+SSM)的宠物领养管理系统(论文+PPT)

基于&#xff08;JavaWebSSM&#xff09;的宠物领养管理系统&#xff08;论文PPT&#xff09; 项目简介项目获取开发环境项目技术运行截图 项目简介 这是一个基于ssm的宠物领养系统 本系统分为前台系统、管理员、收养者和寄养者4个功能模块。 前台系统&#xff1a;游客打开系统…

八、访存顺序(Memory Ordering)

前言 这部分的内容比较抽象&#xff0c;很多内容我无法理解&#xff0c;都是直接翻译过来的。虽然难&#xff0c;但是不可不看&#xff0c;如果遇到无法理解的都直接跳过&#xff0c;那后面都无法学习下去了。觉得无法理解是因为目前的知识还很欠缺&#xff0c;到后面具备了这…

大创项目推荐 题目:基于深度学习的手势识别实现

文章目录 1 前言2 项目背景3 任务描述4 环境搭配5 项目实现5.1 准备数据5.2 构建网络5.3 开始训练5.4 模型评估 6 识别效果7 最后 1 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 基于深度学习的手势识别实现 该项目较为新颖&#xff0c;适合作为竞赛课题…

在Linux下搭建自己的私有maven库并部署和发布自定义jar依赖和自定义maven插件(三)开发和发布自己开发的maven插件

系列文章目录 在Linux下搭建自己的私有maven库并部署和发布自定义jar依赖和自定义maven插件(二)发布自己开发的jar包 文章目录 系列文章目录在Linux下搭建自己的私有maven库并部署和发布自定义jar依赖和自定义maven插件(二)发布自己开发的jar包 前言一、插件需求二、maven自定…

算法基础,一维,二维前缀和差分详解

目录 1.前缀和 1.一维前缀和 例题&#xff1a;【模板】前缀和 2.二维前缀和 例题&#xff1a;【模板】二维前缀和 2.差分 1.一维差分 1.性质&#xff1a;d[i]的前缀和等于a[i] 2.性质&#xff1a;后缀区间修改 例题&#xff1a;【模板】差分 2.二维差分 例题&#x…

(已解决)spingboot 后端发送QQ邮箱验证码

打开QQ邮箱pop3请求服务&#xff1a;&#xff08;按照QQ邮箱引导操作&#xff09; 导入依赖&#xff08;不是maven项目就自己添加jar包&#xff09;&#xff1a; <!-- 邮件发送--><dependency><groupId>org.springframework.boot</groupId><…

谷粒商城【成神路】-【4】——分类维护

目录 1.删除功能的实现 2.新增功能的实现 3.修改功能的实现 4.拖拽功能 1.删除功能的实现 1.1逻辑删除 逻辑删除&#xff1a;不删除数据库中真实的数据&#xff0c;用指定字段&#xff0c;显示的表示是否删除 1.在application.yml中加入配置 mybatis-plus:global-config:…

C语言:内存函数(memcpy memmove memset memcmp使用)

和黛玉学编程呀------------- 后续更新的节奏就快啦 memcpy使用和模拟实现 使用 void * memcpy ( void * destination, const void * source, size_t num ) 1.函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。 2.这个函数在遇到 \0 的时候…

关于node.js奇数版本不稳定 将11.x.x升级至16.x.x不成功的一系列问题(一)

据说vue2用16稳定一些 vue3用18好一点&#xff08;但之前我vue3用的16.18.1也可以&#xff09; 为维护之前的老项目 先搞定node版本切换 下载nvm node版本管理工具 https://github.com/coreybutler/nvm-windows/releases 用这个nvm-setup.zip安装包 安之前最好先将之前的nod…

Hadoop:HDFS学习巩固——基础习题及编程实战

一 HDFS 选择题 1.对HDFS通信协议的理解错误的是&#xff1f; A.客户端与数据节点的交互是通过RPC&#xff08;Remote Procedure Call&#xff09;来实现的 B.HDFS通信协议都是构建在IoT协议基础之上的 C.名称节点和数据节点之间则使用数据节点协议进行交互 D.客户端通过一…

搭建frp

1.frp 是什么&#xff1f; frp 是一款高性能的反向代理应用&#xff0c;专注于内网穿透。它支持多种协议&#xff0c;包括 TCP、UDP、HTTP、HTTPS 等&#xff0c;并且具备 P2P 通信功能。使用 frp&#xff0c;您可以安全、便捷地将内网服务暴露到公网&#xff0c;通过拥有公网…

【Mysql】事务的隔离级别与 MVCC

事务隔离级别 我们知道 MySQL 是一个 C/S 架构的服务&#xff0c;对于同一个服务器来说&#xff0c;可以有多个客户端与之连接&#xff0c;每个客户端与服务器连接上之后&#xff0c;就是一个会话&#xff08; Session &#xff09;。每个客户端都可以在自己的会话中向服务器发…

pytorch创建tensor

目录 1. 从numpy创建2. 从list创建3. 创建未初始化tensor4. 设置默认tensor创建类型5. rand/rand_like, randint6. randn生成正态分布随机数7. full8. arange/range9. linspace/logspace10. Ones/zeros/eye11. randperm 1. 从numpy创建 2. 从list创建 3. 创建未初始化tensor T…

LabVIEW核能设施监测

LabVIEW核能设施监测 在核能领域&#xff0c;确保设施运行的安全性和效率至关重要。LabVIEW通过与硬件的紧密集成&#xff0c;为高温气冷堆燃料装卸计数系统以及脉冲堆辐射剂量监测与数据管理系统提供了解决方案。这些系统不仅提高了监测和管理的精确度&#xff0c;也保证了核…

C++弹球游戏:Jump Ball Game

一、下载压缩包 请查看网站C弹球游戏&#xff1a;Jump Ball Game并且下载&#xff0c;可以看到如下界面&#xff1a; 二、匹配图标 把压缩包解压了&#xff1a; 右键点击Jump Ball Game.lnk&#xff0c;点击“属性”它将会是我们要运行的文件。 点击“更改图标”&#xff0c;选…

构建用于预警大型语言模型辅助生物威胁创建的系统

深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领域的领跑者。点击订阅&#xff0c;与未来同行&#xff01; 订阅&#xff1a;https://rengongzhineng.io/ 。 Op…

【Docker篇】Linux安装Docker、docker安装mysql、redis、rabbitmq

1.Linux安装docker 官方帮助文档&#xff1a;Install Docker Engine on CentOS | Docker Docs 1.1安装命令 # 1. 卸载之前的dockersudo yum remove docker \docker-client \docker-client-latest \docker-common \docker-latest \docker-latest-logrotate \docker-logrotate…

基于Python的招聘网站爬虫及可视化的设计与实现

摘要&#xff1a;现在&#xff0c;随着互联网网络的飞速发展&#xff0c;人们获取信息的最重要来源也由报纸、电视转变为了互联网。互联网的广泛应用使网络的数据量呈指数增长&#xff0c;让人们得到了更新、更完整的海量信息的同时&#xff0c;也使得人们在提取自己最想要的信…

Web3生态系统:构建去中心化的数字社会

随着科技的飞速发展&#xff0c;我们正处在迈向数字未来的道路上&#xff0c;而Web3生态系统则成为这一变革的中心。不仅仅是技术的演进&#xff0c;Web3代表着对传统互联网体系的颠覆&#xff0c;致力于构建一个去中心化的数字社会。本文将深入探讨Web3的核心特征、对金融、社…