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

时间:2020-08-01 13:36:15

标签: flutter dart

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

1 个答案:

答案 0 :(得分:1)

您需要 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);

this StackOverflow answer的贡献