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

Apo*_*leo 0 dart flutter

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

Apo*_*leo 5

您需要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);
Run Code Online (Sandbox Code Playgroud)

部分归功于StackOverflow 的回答