推荐使用:Flutter图像裁剪插件 - Image Cropper
import 'package:image_cropper/image_cropper.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _croppedFile;
Future<void> _cropImage() async {
File _imageFile = await ImagePicker().getImage(source: ImageSource.gallery);
if (_imageFile != null) {
_croppedFile = await ImageCropper.cropImage(
sourcePath: _imageFile.path,
ratioX: 1.0,
ratioY: 1.0,
maxWidth: 500,
maxHeight: 500,
// 你可以添加更多的裁剪选项
);
if (_croppedFile != null) {
setState(() {});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Cropper Example'),
),
body: Center(
child: _croppedFile != null ? Image.file(_croppedFile) : Text('No image'),
),
floatingActionButton: FloatingActionButton(
onPressed: _cropImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
这段代码使用了Flutter的Image Cropper插件来实现从图库中选择图片并裁剪的功能。首先,它导入了必要的包,然后定义了一个HomePage
状态fulWidget,在其状态中,它处理了图片选择和裁剪的逻辑。最后,它构建了一个带有浮动按钮的页面,用于触发图片选择。当图片被选中后,用户可以裁剪它并查看裁剪后的图片。
评论已关闭