Flutter图片缩放裁剪插件zoomable_image_cropper的使用

Flutter图片缩放裁剪插件zoomable_image_cropper的使用

GitHub Pub Version GitHub stars

Zoomable Image Cropper 是一个 Flutter 包,它允许用户轻松地缩放和裁剪图像,并提供了一个友好的界面。它非常适合那些需要让用户选择并裁剪图像特定区域的场景。

Demo

特性

  • 放大缩小:用户可以放大和缩小以更好地查看图像。
  • 可拖动的裁剪区域:裁剪区域可以移动,以便选择所需的裁剪区域。
  • 可定制:您可以自定义裁剪器的各种方面,如纵横比、覆盖颜色等。
  • 易于使用:该包提供了简单的 API 来将裁剪器集成到您的 Flutter 应用程序中。

安装

要使用此包,请在 pubspec.yaml 文件中添加 zoomable_image_cropper 作为依赖项。

dependencies:
  zoomable_image_cropper: ^0.1.0 # 使用 pub.dev 上的最新版本

然后,在 Dart 代码中导入该包:

import 'package:zoomable_image_cropper/zoomable_image_cropper.dart';

使用

以下是如何在 Flutter 应用程序中使用 Zoomable Image Cropper 的基本示例:

class _MyHomePageState extends State<MyHomePage> {
  ZoomableImageCropperController? controller;

  final boxHeight = 500.0;

  bool loadingImage = true;

  @override
  void initState() {
    getPermissionAndSelectImage().then((value) {
      Size size = MediaQuery.of(context).size;
      setState(() {
        controller = ZoomableImageCropperController(
          image: value.image,
          aspectRatio: value.aspectRatio,
          imageWidth: value.imageWidth,
          imageHeight: value.imageHeight,
          containerHeight: boxHeight,
          onInteractionUpdate: (details) {
            /*
             *  您可以使用这些细节来获取缩放和转换值
             *  并进行相应的处理
             */
          },
          containerWidth: size.width,
        );
        loadingImage = false;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Zoomable cropper Demo'),
      ),
      body: SizedBox(
        height: size.height,
        child: Center(
          child: loadingImage
              ? const CircularProgressIndicator()
              : ZoomableImageCropper(controller: controller!),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final bytes = await controller!.getCurrentCropImageBytes();
          // 使用这些字节保存实际文件或将它们发送到服务器
          print(bytes);
        },
        child: const Icon(Icons.save_alt_outlined),
      ),
    );
  }
}

贡献

欢迎贡献!如果您遇到任何问题或有任何改进的想法,请在 GitHub 存储库中打开一个问题。如果您想贡献代码,请遵循贡献指南。

许可证

该项目在 MIT 许可下发布 - 详情请参阅 LICENSE 文件。


更多关于Flutter图片缩放裁剪插件zoomable_image_cropper的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图片缩放裁剪插件zoomable_image_cropper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 zoomable_image_cropper 插件在 Flutter 中实现图片缩放和裁剪功能的代码示例。

首先,确保在你的 pubspec.yaml 文件中添加 zoomable_image_cropper 依赖:

dependencies:
  flutter:
    sdk: flutter
  zoomable_image_cropper: ^x.y.z  # 请替换为最新版本号

然后,运行 flutter pub get 以获取依赖。

接下来,你可以在你的 Flutter 项目中使用 ZoomableImageCropper。以下是一个完整的示例,展示如何使用这个插件:

import 'package:flutter/material.dart';
import 'package:zoomable_image_cropper/zoomable_image_cropper.dart';
import 'dart:io';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Zoomable Image Cropper Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File? _imageFile;
  CroppedFile? _croppedFile;

  Future<void> _pickImage() async {
    final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
      });
    }
  }

  Future<void> _cropImage() async {
    if (_imageFile == null) return;

    final result = await ZoomableImageCropper().cropImage(
      sourcePath: _imageFile!.path,
      aspectRatioPresets: [
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9
      ],
      androidUiSettings: AndroidUiSettings(
        toolbarTitle: 'Cropper',
        toolbarColor: Colors.deepOrange,
        toolbarWidgetColor: Colors.white,
        initAspectRatio: CropAspectRatioPreset.original,
        lockAspectRatio: false,
      ),
      iosUiSettings: IOSUiSettings(
        minimumAspectRatio: 1.0,
      ),
    );

    if (result != null) {
      setState(() {
        _croppedFile = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Zoomable Image Cropper Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _imageFile == null
                ? Text('No image selected.')
                : Image.file(_imageFile!),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('Pick Image'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _cropImage,
              child: Text('Crop Image'),
            ),
            _croppedFile != null
                ? SizedBox(height: 20)
                : Container(),
            _croppedFile != null
                ? Image.file(_croppedFile!.file)
                : Container(),
          ],
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖导入

    • 导入 flutterzoomable_image_cropper 包。
  2. 主应用

    • MyApp 类定义了应用的根组件。
  3. 主页

    • MyHomePage 是一个有状态的组件,包含图像选择和裁剪的逻辑。
  4. 选择图像

    • _pickImage 方法使用 ImagePicker 从图库中选取图像。
  5. 裁剪图像

    • _cropImage 方法使用 ZoomableImageCropper 进行图像裁剪。你可以配置不同的 UI 设置,例如工具栏标题、颜色、锁定宽高比等。
  6. UI 布局

    • 使用 Column 布局,显示所选图像、选择按钮、裁剪按钮和裁剪后的图像。

这样,你就可以在 Flutter 应用中实现图像的缩放和裁剪功能了。确保你已经添加了 image_picker 依赖,因为 ZoomableImageCropper 需要一个图像文件作为输入。你可以在 pubspec.yaml 中添加以下依赖:

dependencies:
  image_picker: ^x.y.z  # 请替换为最新版本号

同样,运行 flutter pub get 以获取依赖。

回到顶部