flutter将widget保存为图片时图片模糊

业务需求:分享作品时生成关于该作品的图片保存至手机,但发现保存的图片很模糊

解决方案:

1.生成图片相当于将某一widget保存为图片,此操作需要用到以下两个插件:

image_gallery_saver: ^1.7.1    # 图片保存至相册

permission_handler: ^8.2.5    # 权限管理

在 android/app/src/main/AndroidManifest.xml 文件中写入:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

在 ios/Runner/Info.plist 文件中写入:

<key>NSPhotoLibraryAddUsageDescription</key>
<string>请允许APP保存图片到相册</string>

将需要生成图片的widget用RepaintBoundary包裹:

RepaintBoundary(
    key: globalKey,
    child: Container(...)
)

点击保存后执行:

GestureDetector(
    onTap: () async {
        RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
        ui.Image image = await boundary.toImage();
        ByteData byteData =await image.toByteData(format: ui.ImageByteFormat.png);
        if (byteData != null) {
            final result = await ImageGallerySaver.saveImage(
                byteData.buffer.asUint8List(),
                quality: 100,
            );
            Fluttertoast.showToast(
                msg: '图片保存成功', 
                toastLength: Toast.LENGTH_LONG
            );
        }
    },
    child: Container(
        child: Text('保存'),
    )
)

2.执行以上后成功将widget保存为图片,但图片很模糊,因此将点击事件中的部分代码进行修改:

ui.Image image = await boundary.toImage(
    //官方代码默认这里pixelRatio=1,将其改为window.devicePixelRatio即可提高图片清晰度
    pixelRatio: ui.window.devicePixelRatio
); 

猜你喜欢

转载自blog.csdn.net/YML_426/article/details/126283238