svg - 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,我会很好。但这是可选的。
解决方案
从自述文件:
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 的作者/主要维护者。
推荐阅读
- mysql - 错误代码:2013。在使用运算符查询期间丢失与 MySQL 服务器的连接 - 或
- r - 通过 R 中的多个变量对纵向数据集进行子集化
- tsql - 报告后面的 SQL 发生了变化,但返回的记录集没有,这是一个问题吗?
- google-apps-script - GOOGLE BUSINESS - 如何为我的网站设置网站图标?
- graph - 通过在简化图中查找模式来计算 ARI
- python - Jupyter:内核似乎已经死了。它会自动重启
- hyperledger-fabric - 超级账本结构设计
- java - Mockito.invokeMethod:我可以将功能接口的实现作为参数传递吗?
- c# - c# regex 只获取字符串中的负数
- azure - Azure Kudu 在 2.2.1 sdk 发布后无法恢复包