Flutter图片裁剪插件flutter_image_cropper的使用

Flutter图片裁剪插件flutter_image_cropper的使用

在Flutter开发中,有时我们需要对图片进行裁剪操作。flutter_image_cropper 是一个非常方便的插件,可以帮助我们轻松实现图片裁剪功能。

特性

  • 简单易用:提供了直观的API来处理图片裁剪。
  • 支持多种比例:可以根据需求设置裁剪框的比例。

使用方法

flutter_image_cropper 插件的使用示例可以在 /example 文件夹中找到。

示例代码

以下是一个完整的示例代码,展示了如何使用 flutter_image_cropper 插件来裁剪图片。

import 'package:flutter/material.dart';
import 'package:flutter_image_cropper/controller/crop_controller.dart';
import 'package:flutter_image_cropper/flutter_image_cropper.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 初始化图片
  Image _image = Image.asset('images/test_image.jpg');

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          // 显示原始图片
          SizedBox(
            height: MediaQuery.of(context).size.height / 2,
            width: MediaQuery.of(context).size.width / 2,
            child: _image,
          ),
          // 裁剪按钮
          Center(
            child: Padding(
              padding: const EdgeInsets.all(6.0),
              child: ElevatedButton(
                onPressed: () async {
                  // 调用裁剪方法
                  var croppedImage = await CropImage.cropImage(
                      context: context,
                      image: Image.asset('images/test_image.jpg'));

                  // 更新UI
                  setState(() {
                    _image = Image(
                      image: croppedImage.image,
                      fit: BoxFit.contain,
                    );
                  });
                },
                child: const Text("Open Cropper"),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

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

1 回复

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


flutter_image_cropper 是一个用于在 Flutter 应用中裁剪图片的插件。它支持从相册或相机中选择图片,并提供多种裁剪选项。以下是如何使用 flutter_image_cropper 插件的详细步骤。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_image_cropper 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.8.5+3
  image_cropper: ^1.5.0

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

2. 配置 Android 和 iOS

Android

android/app/src/main/AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

iOS

ios/Runner/Info.plist 文件中添加以下权限:

<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select images.</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera to take photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>We need access to your microphone to record videos.</string>

3. 使用 image_picker 选择图片

首先,使用 image_picker 插件从相册或相机中选择图片:

import 'package:image_picker/image_picker.dart';

final picker = ImagePicker();

Future<void> pickImage() async {
  final pickedFile = await picker.getImage(source: ImageSource.gallery);

  if (pickedFile != null) {
    // 调用裁剪方法
    cropImage(pickedFile.path);
  }
}

4. 使用 flutter_image_cropper 裁剪图片

接下来,使用 flutter_image_cropper 插件对选中的图片进行裁剪:

import 'package:image_cropper/image_cropper.dart';

Future<void> cropImage(String imagePath) async {
  final croppedFile = await ImageCropper.cropImage(
    sourcePath: imagePath,
    aspectRatioPresets: [
      CropAspectRatioPreset.square,
      CropAspectRatioPreset.ratio3x2,
      CropAspectRatioPreset.original,
      CropAspectRatioPreset.ratio4x3,
      CropAspectRatioPreset.ratio16x9,
    ],
    androidUiSettings: AndroidUiSettings(
      toolbarTitle: 'Crop Image',
      toolbarColor: Colors.deepOrange,
      toolbarWidgetColor: Colors.white,
      initAspectRatio: CropAspectRatioPreset.original,
      lockAspectRatio: false,
    ),
    iosUiSettings: IOSUiSettings(
      title: 'Crop Image',
    ),
  );

  if (croppedFile != null) {
    // 处理裁剪后的图片
    print('Cropped image path: ${croppedFile.path}');
  }
}

5. 完整示例

以下是一个完整的示例,展示了如何从相册中选择图片并进行裁剪:

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

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

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

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

class _ImageCropperExampleState extends State<ImageCropperExample> {
  String _imagePath;

  Future<void> pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      cropImage(pickedFile.path);
    }
  }

  Future<void> cropImage(String imagePath) async {
    final croppedFile = await ImageCropper.cropImage(
      sourcePath: imagePath,
      aspectRatioPresets: [
        CropAspectRatioPreset.square,
        CropAspectRatioPreset.ratio3x2,
        CropAspectRatioPreset.original,
        CropAspectRatioPreset.ratio4x3,
        CropAspectRatioPreset.ratio16x9,
      ],
      androidUiSettings: AndroidUiSettings(
        toolbarTitle: 'Crop Image',
        toolbarColor: Colors.deepOrange,
        toolbarWidgetColor: Colors.white,
        initAspectRatio: CropAspectRatioPreset.original,
        lockAspectRatio: false,
      ),
      iosUiSettings: IOSUiSettings(
        title: 'Crop Image',
      ),
    );

    if (croppedFile != null) {
      setState(() {
        _imagePath = croppedFile.path;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Cropper Example'),
      ),
      body: Center(
        child: _imagePath == null
            ? Text('No image selected.')
            : Image.file(File(_imagePath)),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: pickImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}
回到顶部