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

flutter开发实战-RepaintBoundary实现Widget截图功能

flutter开发实战-RepaintBoundary实现Widget截图功能

在开发中,遇到需要使用截图,像iOS可以截图UIView获取到UIImage,在flutter中可以使用RepaintBoundary实现截图功能

相机拍摄的图片:
在这里插入图片描述

RepaintBoundary截图后的图片
在这里插入图片描述

一、RepaintBoundary

RepaintBoundary是绘制边界。

如果CustomPaint有子节点,为了避免子节点不必要的重绘并提高性能,通常情况下都会将子节点包裹在RepaintBoundary组件中,这样会在绘制时就会创建一个新的绘制层(Layer),其子组件将在新的Layer上绘制,而父组件将在原来Layer上绘制,也就是说RepaintBoundary 子组件的绘制将独立于父组件的绘制,RepaintBoundary会隔离其子节点和CustomPaint本身的绘制边界。示例如下:


CustomPaint(size: Size(300, 300), //指定画布大小painter: MyPainter(),child: RepaintBoundary(child:...)), 
)

参考:https://book.flutterchina.club/chapter10/custom_paint.html#_10-4-1-custompaint

二、实现Widget截图

实现Widget截图,需要将Widget嵌套在RepaintBoundary里,需要用到Globalkey
示例如下

Container(width: widget.width,height: widget.height,clipBehavior: Clip.hardEdge,decoration: BoxDecoration(color: Colors.transparent,),child: RepaintBoundary(key: _cameraViewGlobalKey,child: Transform.scale(scale: scale * aspectRatio,child: AspectRatio(aspectRatio: aspectRatio,child: Center(child: CameraPreview(controller!,),),),),),);

实现截图功能

// 根据GlobalKey来截图Widgetstatic Future<Uint8List?> makeImageUInt8List(GlobalKey globalKey) async {RenderRepaintBoundary boundary =globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;// 这个可以获取当前设备的像素比var dpr = ui.window.devicePixelRatio;ui.Image image = await boundary.toImage(pixelRatio: dpr);ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);Uint8List? pngBytes = byteData?.buffer.asUint8List();return pngBytes;}

获得Uint8List,可以直接将其写入文件或者使用Image展示。

          if (uInt8List != null) {await File(imagePath).writeAsBytes(uInt8List);}

三、小结

flutter开发实战-RepaintBoundary实现Widget截图功能,像iOS可以截图UIView获取到UIImage,在flutter中可以使用RepaintBoundary实现截图功能。

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

相关文章:

  • vue中路由懒加载的写法
  • 【Spring MVC】小文件上传的多种方法
  • UE5.1移动端PreintegratedSkinBxDF解析
  • WebSocket心跳机制(笔记大全)
  • Spring Boot日志:SLF4J和Logback
  • [C++] C++入门第二篇 -- 引用 -- 内联函数inline -- auto+for
  • Latex | 将MATLAB图并导入Latex中的方法
  • JSON格式Python,Java,PHP等封装根据关键词搜索获取淘宝商品列表数据API
  • MySQL MHA高可用配置及故障切换
  • PHP8知识详解:PHP8开发工具VS Code的安装
  • Sui Move与标准Move的有哪些区别和根本性创新
  • 构建自己的ChatGPT:从零开始构建个性化语言模型
  • 【react】react18的学习(十二)– 底层原理(二)之 迭代器 iterator
  • 一遍过JavaSE基础知识
  • 【云原生】Kubernetes之ConfigMap
  • 8.python设计模式【组合模式】
  • tkinter制作任意图形窗口
  • 视频监控综合管理平台EasyCVR多分屏默认播放协议的配置优化
  • 2023杭电多校第三场 1012.Noblesse Code
  • ubuntu qt 环境变量配置
  • 按照Vue写WPF(0):功能实现
  • vb+ACCESS教师管理系统设计设计与实现
  • C++笔记之对指针类型的变量进行+1操作
  • 第六章 游标
  • Github上方导航栏介绍
  • 【vue3+ts】TypeError: Cannot read properties of undefined (reading ‘commit‘)
  • seq2seq、attention、self-attention、transformer、bert
  • 07.计算机网络——数据链路层
  • 海外服务器推荐:国外高性能服务器免费
  • Python基于PyTorch实现卷积神经网络分类模型(CNN分类算法)项目实战