Flutter-如何将SVG文件转换为位图

阿波罗

如何将SVG文件从Flutter资产转换为位图?

阿波罗

您需要flutter_svg库,如果正在使用SVG,可能已经使用过。

您还需要图库。


    import 'package:bitmap/bitmap.dart';
    import 'package:flutter_svg/flutter_svg.dart';

    String svgString = await DefaultAssetBundle.of(context).loadString(svg_path);
    DrawableRoot svgDrawableRoot = await svg.fromSvgString(svgString, null);
    
    // to have a nice rendering it is important to have the exact original height and width,
    // the easier way to retrieve it is directly from the svg string
    // but be careful, this is an ugly fix for a flutter_svg problem that works
    // with my images
    String temp = svgString.substring(svgString.indexOf('height="')+8);
    int originalHeight = int.parse(temp.substring(0, temp.indexOf('p')));
    temp = svgString.substring(svgString.indexOf('width="')+7);
    int originalWidth = int.parse(temp.substring(0, temp.indexOf('p')));

    // toPicture() and toImage() don't seem to be pixel ratio aware, so we calculate the actual sizes here
    double devicePixelRatio = MediaQuery.of(context).devicePixelRatio;

    double width = originalHeight * devicePixelRatio; // where 32 is your SVG's original width
    double height = originalWidth * devicePixelRatio; // same thing

    // Convert to ui.Picture
    ui.Picture picture = svgDrawableRoot.toPicture(size: Size(width, height));

    // Convert to ui.Image. toImage() takes width and height as parameters
    // you need to find the best size to suit your needs and take into account the screen DPI
    ui.Image image = await picture.toImage(width.toInt(), height.toInt());
    ByteData bytes = await image.toByteData(format: ui.ImageByteFormat.png);

    // finally to Bitmap
    Bitmap bitmap = await Bitmap.fromHeadless(width.toInt(), height.toInt(),
        bytes.buffer.asUint8List()
    );

    // if you need to save it:
    File file = File('temporary_file_path/unique_name.bmp');
    file.writeAsBytesSync(bitmap.content);

一些对此StackOverflow答案的感谢

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章