Flutter图片裁剪插件native_image_cropper_macos的使用
Flutter图片裁剪插件native_image_cropper_macos的使用
native_image_cropper_macos
是 native_image_cropper
插件的 MacOS 实现。该插件允许您在 MacOS 平台上对图像进行裁剪操作。本文将介绍如何在 Flutter 应用中使用这个插件,并提供一个完整的示例 Demo。
使用方法
由于 native_image_cropper_macos
是一个被认可的联邦插件,您可以直接使用 native_image_cropper
,该插件会在您的应用中自动包含相应的 MacOS 实现。
示例代码
以下是一个完整的示例代码,展示了如何在 MacOS 上使用 native_image_cropper_macos
进行图像裁剪:
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:native_image_cropper_macos/native_image_cropper_macos.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
static const String imageName = 'sail-boat';
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _nativeImageCropperMacOSPlugin = NativeImageCropperMacOS();
ImageFormat _format = ImageFormat.jpg;
@override
Widget build(BuildContext context) {
return CupertinoApp(
theme: CustomThemes.theme,
home: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
heroTag: 'home',
transitionBetweenRoutes: false,
middle: Text(
'Native Image Cropper MacOS Example',
style: TextStyle(color: CupertinoColors.white),
),
),
child: FutureBuilder<Uint8List>(
future: _getBytes(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final bytes = snapshot.data!;
return Column(
children: [
Expanded(
child: Image(
image: MemoryImage(bytes),
fit: BoxFit.contain,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Flexible(
flex: 2,
child: ImageFormatSlider(
onValueChanged: (value) => setState(() {
_format = value;
}),
),
),
Flexible(
child: CupertinoIconButton(
icon: const Icon(
CupertinoIcons.crop,
color: CupertinoColors.black,
),
onPressed: () => _crop(
context: context,
bytes: bytes,
method: _nativeImageCropperMacOSPlugin.cropRect,
),
),
),
Flexible(
child: CupertinoIconButton(
shape: BoxShape.circle,
icon: const Icon(
CupertinoIcons.crop,
color: CupertinoColors.black,
),
onPressed: () => _crop(
context: context,
bytes: bytes,
method: _nativeImageCropperMacOSPlugin.cropOval,
),
),
),
],
),
],
);
}
return const Center(
child: CupertinoActivityIndicator(),
);
},
),
),
);
}
Future<void> _crop({
required BuildContext context,
required Uint8List bytes,
required Future<Uint8List> Function({
required Uint8List bytes,
required int x,
required int y,
required int width,
required int height,
required ImageFormat format,
}) method,
}) async {
final croppedBytes = await method(
bytes: bytes,
x: 1200,
y: 900,
width: 600,
height: 600,
format: _format,
);
if (mounted) {
Navigator.push<void>(
context,
CupertinoPageRoute(
builder: (context) =>
ResultPage(bytes: croppedBytes, format: _format),
),
);
}
}
Future<Uint8List> _getBytes() async {
final byteData = await rootBundle.load('assets/${MyApp.imageName}.png');
return byteData.buffer.asUint8List();
}
}
// 自定义的图像格式滑块组件
class ImageFormatSlider extends StatelessWidget {
final ValueChanged<ImageFormat> onValueChanged;
const ImageFormatSlider({Key? key, required this.onValueChanged})
: super(key: key);
@override
Widget build(BuildContext context) {
return CupertinoSlider(
min: 0,
max: 1,
divisions: 1,
onChanged: (value) {
onValueChanged(value == 0 ? ImageFormat.jpg : ImageFormat.png);
},
);
}
}
// 自定义的 CupertinoIconButton 组件
class CupertinoIconButton extends StatelessWidget {
final Widget icon;
final VoidCallback onPressed;
final ShapeBorder? shape;
const CupertinoIconButton({
Key? key,
required this.icon,
required this.onPressed,
this.shape,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Container(
decoration: BoxDecoration(shape: shape ?? BoxShape.rectangle),
child: icon,
),
);
}
}
// 结果页面
class ResultPage extends StatelessWidget {
final Uint8List bytes;
final ImageFormat format;
const ResultPage({Key? key, required this.bytes, required this.format})
: super(key: key);
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Cropped Image'),
),
child: Center(
child: Image.memory(bytes),
),
);
}
}
// 自定义主题
class CustomThemes {
static final theme = const CupertinoThemeData().copyWith(
primaryColor: CupertinoColors.systemBlue,
);
}
关键点解释
-
导入必要的包:
package:flutter/cupertino.dart
package:native_image_cropper_macos/native_image_cropper_macos.dart
-
初始化插件实例:
final _nativeImageCropperMacOSPlugin = NativeImageCropperMacOS();
-
加载图像数据:
final byteData = await rootBundle.load('assets/${MyApp.imageName}.png'); return byteData.buffer.asUint8List();
-
调用裁剪方法:
cropRect
:矩形裁剪。cropOval
:椭圆裁剪。
-
显示结果: 裁剪后的图像通过
Navigator.push
方法导航到新的页面展示。
注意事项
- 确保您的项目中已添加
native_image_cropper
和native_image_cropper_macos
依赖。 - 在
pubspec.yaml
文件中添加相应的依赖项:dependencies: flutter: sdk: flutter native_image_cropper: ^latest_version native_image_cropper_macos: ^latest_version
更多关于Flutter图片裁剪插件native_image_cropper_macos的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter图片裁剪插件native_image_cropper_macos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用native_image_cropper_macos
插件进行图片裁剪的示例代码。这个插件允许你在macOS平台上裁剪图片。
首先,确保你已经在pubspec.yaml
文件中添加了native_image_cropper
和native_image_cropper_macos
依赖:
dependencies:
flutter:
sdk: flutter
native_image_cropper: ^x.x.x # 请替换为最新版本号
dependency_overrides:
native_image_cropper_macos:
git:
url: https://github.com/hnvn/flutter_image_cropper.git
path: packages/native_image_cropper_macos # 确保路径正确,或者根据最新版本调整
请注意,由于Flutter插件的更新频率较高,上述依赖路径可能会有所不同,请根据实际情况进行调整,或者查阅官方文档获取最新版本信息。
接下来,在你的Flutter项目中,你可以按照以下步骤使用native_image_cropper_macos
进行图片裁剪:
- 导入必要的包:
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:native_image_cropper/native_image_cropper.dart';
- 定义裁剪配置:
final CropOptions cropOptions = CropOptions(
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,
),
);
注意:由于native_image_cropper_macos
与iOS和Android的UI设置有所不同,你可能需要为macOS平台单独定义UI设置,但当前示例中主要关注裁剪功能本身。
- 选择并裁剪图片:
void _pickAndCropImage() async {
final ImagePicker _picker = ImagePicker();
PickedFile? imageFile = await _picker.pickImage(source: ImageSource.gallery);
if (imageFile != null) {
File? croppedFile = await NativeImageCropper().cropImage(
sourcePath: imageFile.path,
cropOptions: cropOptions,
);
if (croppedFile != null) {
// 在此处处理裁剪后的图片,例如显示或保存
setState(() {
_croppedImagePath = croppedFile.path;
});
}
}
}
- 在UI中显示裁剪后的图片:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String? _croppedImagePath;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Image Cropper Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _pickAndCropImage,
child: Text('Pick and Crop Image'),
),
if (_croppedImagePath != null)
Image.file(
File(_croppedImagePath!),
width: 300,
height: 300,
),
],
),
),
),
);
}
}
- 运行你的应用:
确保你的开发环境已经配置好Flutter和Dart,然后在你的项目根目录下运行flutter run
即可在macOS模拟器或真机上测试图片裁剪功能。
请注意,由于Flutter和插件的更新,上述代码可能需要根据最新版本的API进行调整。建议查阅native_image_cropper
和native_image_cropper_macos
的官方文档以获取最新信息。