当前位置: 首页 > news >正文

Flutter 图片选取及裁剪

在开发项目里修改用户头像的功能,涉及到图片选取及裁剪,基本实现步骤如下:

1、pubspec.yaml 添加 image_picker: ^1.0.1  image_cropper: ^4.0.1:

dependencies:image_picker: ^1.0.1image_cropper: ^4.0.1flutter:sdk: flutter

2、AndroidManifest.xml 添加:

<activityandroid:name="com.yalantis.ucrop.UCropActivity"android:screenOrientation="portrait"android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

3、封装工具类 image_picker_helper.dart ,代码如下:

import 'dart:io';import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';/// @description: 从相册或照相机里选取图片的工具,带裁剪功能
class ImagePickerHelper {BuildContext buildContext;ImagePickerHelper(this.buildContext);void pickImage(ImageSource source, ImagePickerCallback? callback) {ImagePicker().pickImage(source: source).then((image) {if (image == null) return;if (callback == null) return;callback.call(image);}).onError((error, stackTrace) {debugPrint("获取图片失败:$error");});}void cropImage(File originalImage, ImageCropCallback? callback) {Future<CroppedFile?> future = ImageCropper().cropImage(sourcePath: originalImage.path,maxWidth: 100,maxHeight: 100,uiSettings: [AndroidUiSettings(toolbarTitle: '',toolbarColor: Colors.white,statusBarColor: Colors.white,toolbarWidgetColor: Colors.green,initAspectRatio: CropAspectRatioPreset.square,lockAspectRatio: false),IOSUiSettings(title: '',),WebUiSettings(context: buildContext,),],);future.then((value) {debugPrint("_cropImage path:${value == null ? "" : value.path}");if (value == null) return;if (callback == null) return;callback.call(value);}).onError((error, stackTrace) {debugPrint("裁剪图片失败:$error");});}void pickWithCropImage(ImageSource source, ImageCropCallback? callback) {pickImage(source, (xFile) {cropImage(File(xFile.path), callback);});}
}typedef ImagePickerCallback = void Function(XFile xFile);
typedef ImageCropCallback = void Function(CroppedFile croppedFile);

4、使用示例:

//ImageSource.camera 照相机 或 ImageSource.gallery 相册ImagePickerHelper(context).pickWithCropImage(ImageSource.gallery,(croppedFile) {//获取到剪切的文件路径,进行相关的操作debugPrint("croppedFile:${croppedFile.path}");});

http://www.lryc.cn/news/107399.html

相关文章:

  • C语言每日一题:11.《数据结构》链表分割。
  • 记一次Oracle归档日志异常增长问题的排查过程
  • Java设计模式——类之间的关系
  • Dockerfile构建Redis镜像
  • C高级DAY2
  • Linux 服务管理
  • 问题记录 1 页面初始化触发el-form必填校验
  • 后端整理(JVM、Redis、反射)
  • 1. CUDA中的grid和block
  • 宝存科技企业级固态硬盘解决方案助力企业应用性能提升
  • 《练习100》31~35
  • 额外题目第4天|132 673 841 127 684 657
  • HTTP 状态码的分类和含义
  • Linux Bridge(网桥)
  • 【数据结构】优先队列
  • 如何在 Ubuntu 22.04 下编译 StoneDB for MySQL 8.0 | StoneDB 使用教程 #1
  • AMEYA360:尼得科科宝旋转型DIP开关系列汇总
  • 为什么感觉 C/C++ 不火了?
  • 【Linux】在服务器上创建Crontab(定时任务),自动执行shell脚本
  • 内存分析工具之Mat
  • 【逗老师的PMP学习笔记】项目的运行环境
  • Rust- 模块
  • 【开源源码学习】
  • CNN-NER论文详解
  • 利用ChatGPT制作行业应用:哪些行业最受益
  • 【SA8295P 源码分析】60 - QNX Host 如何新增 android_test 分区给 Android GVM 挂载使用
  • Linux 用户和权限
  • 分布式应用:ELFK集群部署
  • Quartz使用文档,使用Quartz实现动态任务,Spring集成Quartz,Quartz集群部署,Quartz源码分析
  • Go -- 测试 and 项目实战