Flutter图片裁剪插件simple_image_crop的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter图片裁剪插件simple_image_crop的使用

在Flutter中,simple_image_crop 是一个简单易用的插件,用于在iOS和Android平台上对图片进行裁剪。它支持圆形和矩形两种裁剪区域,并且可以调整裁剪后的图片质量和大小。

安装

首先,在项目的 pubspec.yaml 文件中添加 simple_image_crop 插件作为依赖项:

dependencies:
  simple_image_crop: ^0.2.0

然后运行以下命令以安装依赖:

flutter pub get

使用

创建一个加载和编辑图片的小部件

我们可以通过 ImgCrop 小部件来加载和编辑图片。图片可以来自任何类型,例如文件路径或资产资源。

final cropKey = GlobalKey<ImgCropState>();

Widget _buildCropImage() {
  return Container(
    color: Colors.black,
    child: ImgCrop(
      key: cropKey,
      chipRadius: 150,  // 裁剪区域的半径
      chipShape: 'circle', // 裁剪类型为 "circle" 或 "rect"
      image: FileImage(imageFile), // 你选择的图片文件
    ),
  );
}

生成裁剪后的图片

通过调用 cropCompleted 方法,可以获取裁剪后的图片文件。这是一个异步函数,返回裁剪后的图片文件。

final croppedFile = await crop.cropCompleted(
  croppedImage,
  {pictureQuality: 900} // 控制图片的大小和质量
);

完整的示例代码如下:

import 'dart:io';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:simple_image_crop/simple_image_crop.dart';

enum _sheetType { gallery, camera }

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      initialRoute: "/",
      routes: {
        "crop_page": (context) => SimpleCropRoute(),
        "/": (context) => MyHomeRoute()
      },
    );
  }
}

class MyHomeRoute extends StatefulWidget {
  [@override](/user/override)
  _MyHomeRouteState createState() => new _MyHomeRouteState();
}

class _MyHomeRouteState extends State<MyHomeRoute> {
  final cropKey = GlobalKey<ImgCropState>();

  Future getImage(type) async {
    var image = await ImagePicker.pickImage(
        source: type == _sheetType.gallery
            ? ImageSource.gallery
            : ImageSource.camera);
    if (image == null) return;
    Navigator.of(context).pop();
    Navigator.of(context).pushNamed('crop_page', arguments: {'image': image});
  }

  void _showActionSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min, // 设置最小的弹出
              children: <Widget>[
                new ListTile(
                  leading: new Icon(Icons.photo_camera),
                  title: new Text("相机拍照"),
                  onTap: () async {
                    getImage(_sheetType.camera);
                  },
                ),
                new ListTile(
                  leading: new Icon(Icons.photo_library),
                  title: new Text("相册选择"),
                  onTap: () async {
                    getImage(_sheetType.gallery);
                  },
                ),
              ],
            ),
          );
        });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('选择图片'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showActionSheet,
        tooltip: '增加',
        child: Icon(Icons.add),
      ),
    );
  }
}

class SimpleCropRoute extends StatefulWidget {
  [@override](/user/override)
  _SimpleCropRouteState createState() => _SimpleCropRouteState();
}

class _SimpleCropRouteState extends State<SimpleCropRoute> {
  final cropKey = GlobalKey<ImgCropState>();

  Future<void> showImage(BuildContext context, File file) async {
    new FileImage(file)
        .resolve(new ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool _) {
      print('-------------------------------------------$info');
    }));
    return showDialog<void>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
              title: Text(
                '当前截图:',
                style: TextStyle(
                    fontFamily: 'Roboto',
                    fontWeight: FontWeight.w300,
                    color: Theme.of(context).primaryColor,
                    letterSpacing: 1.1),
              ),
              content: Image.file(file));
        });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final Map args = ModalRoute.of(context).settings.arguments;
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          title: Text(
            '缩放与裁剪',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          leading: new IconButton(
            icon:
                new Icon(Icons.navigate_before, color: Colors.black, size: 40),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: Center(
          child: ImgCrop(
            key: cropKey,
            chipRadius: 100,
            chipShape: ChipShape.rect,
            chipRatio: 2 / 1,
            maximumScale: 3,
            image: FileImage(args['image']),
            // handleSize: 0.0,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            final crop = cropKey.currentState;
            final croppedFile =
                await crop.cropCompleted(args['image'], preferredSize: 1000);
            showImage(context, croppedFile);
          },
          tooltip: '增加',
          child: Text('裁剪'),
        ));
  }
}

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

1 回复

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


simple_image_crop 是一个简单易用的 Flutter 插件,用于裁剪图片。它提供了基本的图片裁剪功能,并且易于集成到你的 Flutter 项目中。下面是使用 simple_image_crop 插件的步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 simple_image_crop 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_image_crop: ^1.0.0

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 simple_image_crop 插件:

import 'package:simple_image_crop/simple_image_crop.dart';

3. 使用 SimpleImageCrop 组件

SimpleImageCrop 是一个用于裁剪图片的组件。你可以将它添加到你的页面中,并传入需要裁剪的图片。

class ImageCropPage extends StatefulWidget {
  [@override](/user/override)
  _ImageCropPageState createState() => _ImageCropPageState();
}

class _ImageCropPageState extends State<ImageCropPage> {
  final _cropKey = GlobalKey<SimpleImageCropState>();
  File? _croppedImage;

  Future<void> _cropImage() async {
    final cropState = _cropKey.currentState;
    if (cropState != null) {
      final croppedFile = await cropState.crop();
      setState(() {
        _croppedImage = croppedFile;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Crop'),
      ),
      body: Column(
        children: [
          Expanded(
            child: SimpleImageCrop(
              key: _cropKey,
              image: AssetImage('assets/sample_image.jpg'), // 替换为你的图片路径
            ),
          ),
          ElevatedButton(
            onPressed: _cropImage,
            child: Text('Crop Image'),
          ),
          if (_croppedImage != null)
            Image.file(_croppedImage!),
        ],
      ),
    );
  }
}

4. 运行项目

现在你可以运行你的 Flutter 项目,并查看图片裁剪功能是否正常工作。

5. 其他功能

simple_image_crop 还提供了一些其他功能,例如设置裁剪框的宽高比、旋转图片等。你可以通过查阅插件的文档来了解更多详细信息。

6. 处理裁剪后的图片

裁剪后的图片会以 File 对象的形式返回,你可以将其保存到本地、上传到服务器或进行其他处理。

7. 注意事项

  • 确保你已经在 pubspec.yaml 文件中正确配置了图片资源路径。
  • 如果你需要从相册或相机获取图片,可以使用 image_picker 插件。

8. 示例代码

以下是一个完整的示例代码,展示了如何使用 simple_image_crop 插件进行图片裁剪:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImageCropPage(),
    );
  }
}

class ImageCropPage extends StatefulWidget {
  [@override](/user/override)
  _ImageCropPageState createState() => _ImageCropPageState();
}

class _ImageCropPageState extends State<ImageCropPage> {
  final _cropKey = GlobalKey<SimpleImageCropState>();
  File? _croppedImage;

  Future<void> _cropImage() async {
    final cropState = _cropKey.currentState;
    if (cropState != null) {
      final croppedFile = await cropState.crop();
      setState(() {
        _croppedImage = croppedFile;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Crop'),
      ),
      body: Column(
        children: [
          Expanded(
            child: SimpleImageCrop(
              key: _cropKey,
              image: AssetImage('assets/sample_image.jpg'), // 替换为你的图片路径
            ),
          ),
          ElevatedButton(
            onPressed: _cropImage,
            child: Text('Crop Image'),
          ),
          if (_croppedImage != null)
            Image.file(_croppedImage!),
        ],
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!