flutter 我想在预览时裁剪相机,我该怎么做?

fykwrbwg  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(205)

拍完照片后,我只想看到屏幕上的方形区域。如果需要,我可以添加我的代码。

编辑:这是我的代码。preview.dart。我不能分享所有的代码。Stackoverflow想让我写一篇长文章。preview.dart

import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_ml_kit/google_ml_kit.dart';

class PreviewScreen extends StatefulWidget {
  final XFile imgPath;
  PreviewScreen({this.imgPath});

  @override
  _PreviewScreenState createState() => _PreviewScreenState();
}

class _PreviewScreenState extends State<PreviewScreen> {
  bool textScanning = false;
  XFile imageFile;
  @override
  void initState() {
    super.initState();
    getRecognisedText(XFile(widget.imgPath.path));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: true,
        ),
        body: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Expanded(
                flex: 2,
                child: Image.file(
                  File(widget.imgPath.path),
                  fit: BoxFit.cover,
                ),
              ),
            ],
          ),
        ));
  }

Edit2:这是我的代码。这是我的Camera.dart。我不能分享所有的代码。Stackoverflow想让我写一篇长文章。

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:testcameraproje/screens/preview.dart';

class CameraScreen extends StatefulWidget {
  @override
  _CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
  CameraController cameraController;
  List cameras;
  int selectedCameraIndex;
  String imgPath;

  Future initCamera(CameraDescription cameraDescription) async {
    if (cameraController != null) {
      await cameraController.dispose();
    }

    cameraController =
        CameraController(cameraDescription, ResolutionPreset.high);

    cameraController.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });

    if (cameraController.value.hasError) {
      print('Camera Error ${cameraController.value.errorDescription}');
    }
    try {
      await cameraController.initialize();
    } catch (e) {
      showCameraException(e);
    }

    if (mounted) {
      setState(() {});
    }
  }
  Widget cameraPreview() {
    if (cameraController == null || !cameraController.value.isInitialized) {
      return Text(
        'Loading',
        style: TextStyle(
            color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold),
      );
    }
    return AspectRatio(
      aspectRatio: 100 / 200,
      child: CameraPreview(cameraController),
    );
  }
  Widget cameraControl(context) {
    return Expanded(
      child: Align(
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            FloatingActionButton(
              child: Icon(
                Icons.camera,
                color: Colors.black,
              ),
              backgroundColor: Colors.white,
              onPressed: () {
                onCapture(context);
              },
            )
          ],
        ),
      ),
    );
  }
  Widget cameraToggle() {
    if (cameras == null || cameras.isEmpty) {
      return Spacer();
    }
    CameraDescription selectedCamera = cameras[selectedCameraIndex];
    CameraLensDirection lensDirection = selectedCamera.lensDirection;
    return Expanded(
      child: Align(
        alignment: Alignment.centerLeft,
        child: TextButton.icon(
            onPressed: () {
              onSwitchCamera();
            },
            icon: Icon(
              getCameraLensIcons(lensDirection),
              color: Colors.white,
              size: 24,
            ),
            label: Text(           '${lensDirection.toString().substring(lensDirection.toString().indexOf('.') + 1).toUpperCase()}',
              style:
                  TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
            )),
      ),
    );
  }
  onCapture(context) async {
    try {
      await cameraController.takePicture().then((value) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => PreviewScreen(imgPath: value)));
      });
    } catch (e) {
      showCameraException(e);
    }
  }
  @override
  void initState() {
    super.initState();
    availableCameras().then((value) {
      cameras = value;
      if (cameras.length > 0) {
        setState(() {
          selectedCameraIndex = 0;
        });
        initCamera(cameras[selectedCameraIndex]).then((value) {});
      } else {
        print('No camera available');
      }
    }).catchError((e) {
      print('Error : ${e.code}');
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Container(
        child: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: cameraPreview(),
            ),
            Align(
              alignment: Alignment.topCenter,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    Text('ALANA TUTUN', style: TextStyle(fontSize: 24)),
                  ],
                ),
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: Image.asset(
                'assets/filter.png',
                scale: 0.3,
                width: 200,
                height: 100,
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                height: 120,
                width: double.infinity,
                padding: EdgeInsets.all(15),
                margin: EdgeInsets.only(bottom: 20),
                color: Colors.transparent,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    cameraToggle(),
                    cameraControl(context),
                    Spacer(),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
  getCameraLensIcons(lensDirection) {
    switch (lensDirection) {
      case CameraLensDirection.back:
        return CupertinoIcons.switch_camera;
      case CameraLensDirection.front:
        return CupertinoIcons.switch_camera_solid;
      case CameraLensDirection.external:
        return CupertinoIcons.photo_camera;
      default:
        return Icons.device_unknown;
    }
  }
  onSwitchCamera() {
    selectedCameraIndex =
        selectedCameraIndex < cameras.length - 1 ? selectedCameraIndex + 1 : 0;
    CameraDescription selectedCamera = cameras[selectedCameraIndex];
    initCamera(selectedCamera);
  }
  showCameraException(e) {
    String errorText = 'Error ${e.code} \nError message: ${e.description}';
    print(errorText);
  }
}
iq3niunx

iq3niunx1#

1.手动

使用image_cropper

cropTheImage() async {
    cropImage = true;
    var cropped = (await ImageCropper.platform.cropImage(
      sourcePath: imageFile!.path,  // Enter your imageFile Path here
      uiSettings: [
        AndroidUiSettings(lockAspectRatio: false),
      ],
    ));
    croppedFile = File(cropped!.path);
    setState(() {});
  }

在需要裁剪图像的任何地方调用此函数。
参考:Example1Example2

2.编程方式

Image小部件提供一个fit因子,然后将其 Package 在AspectRatio中。

AspectRatio(
  aspectRatio: 1.5, 
  child: Image.asset(
    'your_image_asset',
    fit: BoxFit.cover,
  ),
)

AspectRatio(
    aspectRatio: 1,
    child: Container(
        decoration: new BoxDecoration(
        image: new DecorationImage(
        fit: BoxFit.fitWidth,
        alignment: FractionalOffset.center, // to get the center 
        image: imageUrl,
       )
      ),
   ),
 ),

参考:How do I crop an image in Flutter?

相关问题