Flutter图片裁剪插件easy_image_cropper的使用
Flutter图片裁剪插件easy_image_cropper的使用
easy_image_cropper
是一个简单的图片裁剪小部件,可以轻松地裁剪头像和其他图片。它确保在iOS和Android上具有一致的裁剪体验。
快速开始 🚀
- 安装这个包。
flutter pub get easy_image_cropper
使用方法
步骤1:创建裁剪UI
使用 ImgCrop
组件来创建裁剪UI。UI的大小由其父容器决定。
///...
Center(
child: ImgCrop(
key: cropKey, // 必须是一个 GlobalKey
chipShape: ChipShape.circle, // 裁剪形状为圆形
maximumScale: 1, // 最大缩放比例
image: FileImage(File(img.path)), // 图片文件
),
)
注意:cropKey
必须是一个 GlobalKey
步骤2:获取裁剪后的图片
final crop = cropKey.currentState;
final croppedFile = await crop.cropCompleted(File(img.path), pictureQuality: 900);
// `pictureQuality` 表示裁剪后图片的质量
示例代码
以下是一个完整的示例代码,展示如何使用 easy_image_cropper
插件进行图片裁剪。
import 'dart:io';
import 'dart:async';
import 'package:easy_image_cropper/easy_image_cropper.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
enum SheetType { gallery, camera }
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: "/",
routes: {
"crop_page": (context) => const SimpleCropRoute(),
"/": (context) => const MyHomeRoute()
},
);
}
}
class MyHomeRoute extends StatefulWidget {
const MyHomeRoute({super.key});
[@override](/user/override)
MyHomeRouteState createState() => MyHomeRouteState();
}
class MyHomeRouteState extends State<MyHomeRoute> {
final cropKey = GlobalKey<ImgCropState>();
final _picker = ImagePicker();
Future getImage(type) async {
var image = await _picker.pickImage(
source: type == SheetType.gallery
? ImageSource.gallery
: ImageSource.camera);
if (image == null) return;
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>[
ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text("photo camera"),
onTap: () async {
getImage(SheetType.camera);
},
),
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text("photo library"),
onTap: () async {
getImage(SheetType.gallery);
},
),
],
),
);
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('select image'),
),
floatingActionButton: FloatingActionButton(
onPressed: _showActionSheet,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class SimpleCropRoute extends StatefulWidget {
const SimpleCropRoute({super.key});
[@override](/user/override)
SimpleCropRouteState createState() => SimpleCropRouteState();
}
class SimpleCropRouteState extends State<SimpleCropRoute> {
final cropKey = GlobalKey<ImgCropState>();
Future<Null> showImage(BuildContext context, File file) async {
return showDialog<Null>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
'Current screenshot:',
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 dynamic args = ModalRoute.of(context)!.settings.arguments;
XFile img = args['image'];
return Scaffold(
appBar: AppBar(
elevation: 0,
title: const Text(
'Zoom and Crop',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
leading: IconButton(
icon: const Icon(Icons.navigate_before,
color: Colors.black, size: 40),
onPressed: () => Navigator.of(context).pop(),
),
),
body: Center(
child: ImgCrop(
key: cropKey,
chipShape: ChipShape.circle,
maximumScale: 1,
image: FileImage(File(img.path)),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final crop = cropKey.currentState;
final croppedFile =
await crop!.cropCompleted(File(img.path), pictureQuality: 900);
showImage(context, croppedFile);
},
tooltip: 'Increment',
child: const Text('Crop'),
));
}
}
更多关于Flutter图片裁剪插件easy_image_cropper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter图片裁剪插件easy_image_cropper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用easy_image_cropper
插件进行图片裁剪的详细代码示例。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加easy_image_cropper
依赖:
dependencies:
flutter:
sdk: flutter
easy_image_cropper: ^2.3.3 # 请根据需要替换为最新版本
然后运行flutter pub get
来安装依赖。
2. 导入必要的包
在你的Dart文件中导入easy_image_cropper
包:
import 'package:easy_image_cropper/easy_image_cropper.dart';
import 'package:image_picker/image_picker.dart'; // 通常与image_picker一起使用
3. 配置权限
由于裁剪功能通常涉及到访问设备的存储,你需要在AndroidManifest.xml
和Info.plist
中配置必要的权限。
对于Android,在AndroidManifest.xml
中添加:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
对于iOS,在Info.plist
中添加:
<key>NSPhotoLibraryUsageDescription</key>
<string>App needs access to photo library</string>
<key>NSCameraUsageDescription</key>
<string>App needs access to the camera</string>
4. 使用插件
下面是一个完整的示例,展示如何从设备中选择图片并进行裁剪:
import 'package:flutter/material.dart';
import 'package:easy_image_cropper/easy_image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Image Cropper Example'),
),
body: Center(
child: ImageCropperScreen(),
),
),
);
}
}
class ImageCropperScreen extends StatefulWidget {
@override
_ImageCropperScreenState createState() => _ImageCropperScreenState();
}
class _ImageCropperScreenState extends State<ImageCropperScreen> {
File? _imageFile;
final ImagePicker _picker = ImagePicker();
Future<void> _pickImage() async {
final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
final croppedFile = await EasyImageCropper.cropImage(
filePath: pickedFile.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,
),
);
setState(() {
if (croppedFile != null) {
_imageFile = croppedFile;
}
});
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _pickImage,
child: Text('Pick and Crop Image'),
),
if (_imageFile != null)
Image.file(
_imageFile!,
width: 300,
height: 300,
fit: BoxFit.cover,
),
],
);
}
}
5. 运行应用
确保所有配置正确后,运行你的Flutter应用。你应该能够选择一个图片并进行裁剪,然后显示裁剪后的图片。
这个示例展示了如何使用easy_image_cropper
插件从设备图库中选择图片并进行裁剪。你可以根据需求进一步自定义裁剪选项和UI设置。