首页 > 解决方案 > Flutter 在 CustomPaint (Canvas) 中绘制 SVG

问题描述

我有这样的事情:

CustomPaint(
       painter: CurvePainter(),
)

在这堂课上,我正在画画:

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import './myState.dart';
import './models/mode.dart';
final String rawSvg = '''<svg viewBox="...">...</svg>''';

class CurvePainter extends CustomPainter {
  MyState _myState;
  DrawableRoot svgRoot;
  CurvePainter(MyState myState) {
    this._myState = myState;
    this.loadAsset();
  }

  void loadAsset() async {
    this.svgRoot = await svg.fromSvgString(rawSvg, rawSvg);// The canvas that is your board.
  }

  @override
  void paint (Canvas canvas, Size size) {
    canvas.translate(_myState.translateX, _myState.translateY);
    if(this.svgRoot != null){
        svgRoot.scaleCanvasToViewBox(canvas, size);
        svgRoot.clipCanvasToViewBox(canvas);
        // svgRoot.draw(canvas, size);
    }
}

有人知道如何在paint方法中绘制SVG吗?我找到了这个库https://pub.dev/packages/flutter_svg#-readme-tab-。使用我的代码出现错误:未处理的异常:状态错误:viewBox 元素必须为 4 个元素长

如果我可以缩放和旋转画布内的 svg,我会很好。但这是可选的。

标签: svgflutterdartpaint

解决方案


自述文件

import 'package:flutter_svg/flutter_svg.dart';
final String rawSvg = '''<svg viewBox="...">...</svg>''';
final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

// If you only want the final Picture output, just use
final Picture picture = svgRoot.toPicture();

// Otherwise, if you want to draw it to a canvas:
// Optional, but probably normally desirable: scale the canvas dimensions to
// the SVG's viewbox
svgRoot.scaleCanvasToViewBox(canvas);

// Optional, but probably normally desireable: ensure the SVG isn't rendered
// outside of the viewbox bounds
svgRoot.clipCanvasToViewBox(canvas);
svgRoot.draw(canvas, size);

您可以将其调整为:

class CurvePainter extends CustomPainter {
  CurvePainter(this.svg);

  final DrawableRoot svg;
  @override
  void paint(Canvas canvas, Size size) {
       canvas.drawLine(...);
       svg.scaleCanvasToViewBox(canvas);
       svg.clipCanvasToViewBox(canvas);
       svg.draw(canvas, size);
  }
}

我建议在您的应用程序中尽早找到一些方法来获取异步部分,可能使用 FutureBuilder 或 ValueListenableBuilder。

披露:我是 Flutter SVG 的作者/主要维护者。


推荐阅读