flutter開(kāi)發(fā)實(shí)戰(zhàn)-RepaintBoundary實(shí)現(xiàn)Widget截圖功能
在開(kāi)發(fā)中,遇到需要使用截圖,像iOS可以截圖UIView獲取到UIImage,在flutter中可以使用RepaintBoundary實(shí)現(xiàn)截圖功能
相機(jī)拍攝的圖片:
RepaintBoundary截圖后的圖片
一、RepaintBoundary
RepaintBoundary是繪制邊界。
如果CustomPaint有子節(jié)點(diǎn),為了避免子節(jié)點(diǎn)不必要的重繪并提高性能,通常情況下都會(huì)將子節(jié)點(diǎn)包裹在RepaintBoundary組件中,這樣會(huì)在繪制時(shí)就會(huì)創(chuàng)建一個(gè)新的繪制層(Layer),其子組件將在新的Layer上繪制,而父組件將在原來(lái)Layer上繪制,也就是說(shuō)RepaintBoundary 子組件的繪制將獨(dú)立于父組件的繪制,RepaintBoundary會(huì)隔離其子節(jié)點(diǎn)和CustomPaint本身的繪制邊界。示例如下:
CustomPaint(
size: Size(300, 300), //指定畫(huà)布大小
painter: MyPainter(),
child: RepaintBoundary(child:...)),
)
參考:https://book.flutterchina.club/chapter10/custom_paint.html#_10-4-1-custompaint
二、實(shí)現(xiàn)Widget截圖
實(shí)現(xiàn)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!,
),
),
),
),
),
);
實(shí)現(xiàn)截圖功能
// 根據(jù)GlobalKey來(lái)截圖Widget
static Future<Uint8List?> makeImageUInt8List(GlobalKey globalKey) async {
RenderRepaintBoundary boundary =
globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary;
// 這個(gè)可以獲取當(dāng)前設(shè)備的像素比
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,可以直接將其寫(xiě)入文件或者使用Image展示。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-614077.html
if (uInt8List != null) {
await File(imagePath).writeAsBytes(uInt8List);
}
三、小結(jié)
flutter開(kāi)發(fā)實(shí)戰(zhàn)-RepaintBoundary實(shí)現(xiàn)Widget截圖功能,像iOS可以截圖UIView獲取到UIImage,在flutter中可以使用RepaintBoundary實(shí)現(xiàn)截圖功能。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-614077.html
到了這里,關(guān)于flutter開(kāi)發(fā)實(shí)戰(zhàn)-RepaintBoundary實(shí)現(xiàn)Widget截圖功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!