CropImagePage.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_image_compress/flutter_image_compress.dart';
  4. import 'package:flutter_habit/common/I18N.dart';
  5. import 'package:image_crop/image_crop.dart';
  6. class CropImagePage extends StatefulWidget {
  7. CropImagePage(this._image);
  8. final File _image; //原始图片路径
  9. @override
  10. _CropImagePageState createState() {
  11. return _CropImagePageState();
  12. }
  13. }
  14. class _CropImagePageState extends State<CropImagePage> {
  15. double? baseLeft; //图片左上角的x坐标
  16. double? baseTop; //图片左上角的y坐标
  17. double? imageWidth; //图片宽度,缩放后会变化
  18. double imageScale = 1; //图片缩放比例
  19. Image? imageView;
  20. final cropKey = GlobalKey<CropState>();
  21. @override
  22. Widget build(BuildContext context) {
  23. return Scaffold(
  24. appBar: AppBar(
  25. title: Text(I18N.of("裁剪图片")),
  26. ),
  27. body: Container(
  28. padding: const EdgeInsets.all(5.0),
  29. color: Theme.of(context).canvasColor,
  30. child: Column(
  31. children: <Widget>[
  32. Expanded(
  33. child: Crop.file(
  34. widget._image,
  35. key: cropKey,
  36. aspectRatio: 1,
  37. alwaysShowGrid: true,
  38. ),
  39. ),
  40. ],
  41. ),
  42. ),
  43. floatingActionButton: FloatingActionButton(
  44. child: Icon(Icons.content_cut),
  45. onPressed: () async {
  46. File result = await ImageCrop.cropImage(
  47. file: widget._image, area: cropKey.currentState!.area!, scale: 1);
  48. List<int> out = await FlutterImageCompress.compressWithList(
  49. (await result.readAsBytes()).toList() as Uint8List,
  50. minWidth: 200,
  51. minHeight: 200,
  52. quality: 95,
  53. );
  54. Navigator.of(context).pop(out);
  55. },
  56. ),
  57. );
  58. }
  59. }