Flutter截圖控件RepaintBoundary案例(一)

記錄一下 RepaintBoundary 控件的簡單使用。這個控件能幫咱們實現截圖的功能,你想截哪一個控件的圖,直接用 RepaintBoundary 把該控件包起來便可。java

關鍵代碼

點擊截圖按鈕所作的事:緩存

該代碼經過_key 找到想要截圖的節點控件,而後轉成 Image,在轉成 bytes 字節,最後存入緩存文件。微信

 //截圖 void _onCaputrePicture() async { try { RenderRepaintBoundary boundary = _key.currentContext.findRenderObject(); double pix = window.devicePixelRatio; // 獲取當前設備的像素比 var image = await boundary.toImage(pixelRatio: pix); ByteData byteData = await image.toByteData(format: ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); Directory tempDir = await getTemporaryDirectory(); //需添加 path_provider: 1.6.11 插件 File file = new File('${tempDir.path}/${_images.length}.png'); print("===》" + file.path); if (!file.existsSync()) { file.createSync(); } file.writeAsBytesSync(pngBytes); //寫入文件 _images.add(file.path); //添加一個路徑 setState(() {}); //刷新界面 } catch (e) { print(e); } }

效果圖

多點了幾下,我就餓了。。。app

所有代碼

import 'dart:io';import 'dart:typed_data';import 'dart:ui';import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:path_provider/path_provider.dart';
class DemoCapturePage extends StatefulWidget { @override _DemoCapturePageState createState() => _DemoCapturePageState();}
class _DemoCapturePageState extends State<DemoCapturePage> { GlobalKey _key = new GlobalKey();
List<String> _images = new List();
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Flutter截圖"), ), body: Column( children: <Widget>[ RepaintBoundary( key: _key, //設置Key child: Container( child: Image.network( "https://visualhunt.com/photos/1/orange-oranges-fruit-sweet-food.jpg?s=l", width: 120, height: 120, ), ), ), RaisedButton( onPressed: () { //截圖 _onCaputrePicture(); }, child: Text("截圖"), ), Expanded( child: GridView.builder( itemCount: _images.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, mainAxisSpacing: 2, crossAxisSpacing: 2, //childAspectRatio: 0.7, ), itemBuilder: (context, index) { Image image = Image.file(File.fromUri(Uri.parse(_images[index]))); return image; }, ), ) ], )); }
//截圖 void _onCaputrePicture() async { try { RenderRepaintBoundary boundary = _key.currentContext.findRenderObject(); double pix = window.devicePixelRatio; // 獲取當前設備的像素比 var image = await boundary.toImage(pixelRatio: pix); ByteData byteData = await image.toByteData(format: ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); Directory tempDir = await getTemporaryDirectory(); //需添加 path_provider: 1.6.11 插件 File file = new File('${tempDir.path}/${_images.length}.png'); print("===》" + file.path); if (!file.existsSync()) { file.createSync(); } file.writeAsBytesSync(pngBytes); //寫入文件 _images.add(file.path); //添加一個路徑 setState(() {}); //刷新界面 } catch (e) { print(e); } }}


本文分享自微信公衆號 - Flutter學習簿(gh_d739155d3b2c)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。async

相關文章
相關標籤/搜索