在Flutter中实现图片裁剪可以使用image_cropper 1.0.0插件。以下是具体实现步骤:
1. 添加依赖
在pubspec.yaml中添加:
dependencies:
image_cropper: ^1.0.0
image_picker: ^0.8.4+4
2. 配置平台设置
Android (android/app/src/main/AndroidManifest.xml):
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
iOS (ios/Runner/Info.plist):
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问相册来选择图片</string>
<key>NSCameraUsageDescription</key>
<string>需要使用相机拍摄图片</string>
3. 实现代码
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
class ImageCropperExample extends StatefulWidget {
@override
_ImageCropperExampleState createState() => _ImageCropperExampleState();
}
class _ImageCropperExampleState extends State<ImageCropperExample> {
File? _croppedFile;
Future<void> _cropImage() async {
final picker = ImagePicker();
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
final croppedFile = await ImageCropper.cropImage(
sourcePath: pickedFile.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9,
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: '裁剪图片',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
),
);
if (croppedFile != null) {
setState(() {
_croppedFile = croppedFile;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('图片裁剪')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_croppedFile != null)
Image.file(_croppedFile!, height: 200),
SizedBox(height: 20),
ElevatedButton(
onPressed: _cropImage,
child: Text('选择并裁剪图片'),
),
],
),
),
);
}
}
主要参数说明
aspectRatioPresets: 预设裁剪比例
androidUiSettings: Android平台UI设置
iosUiSettings: iOS平台UI设置
lockAspectRatio: 是否锁定宽高比
这样就实现了基本的图片裁剪功能,用户可以选择图片并进行裁剪操作。