/// 架构图导出:SVG(矢量,可直接进文档 / 二次编辑)与 PNG(3840×2160 位图)。 /// /// 与其他导出保持同一约定: /// - 导出始终使用**纯白背景**([exportTokens]),与屏幕主题无关; /// - PNG 画布固定 1920×1080 逻辑尺寸 × 2 倍像素; /// - 不导出网格点阵与选中框,只导出设计内容。 library; import 'dart:math' as math; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import '../export/export_fit.dart'; import '../library/symbol_library.dart'; import '../theme/tokens.dart'; import 'arch_models.dart'; import 'arch_painter.dart'; // ===================== PNG ===================== /// 渲染架构图 PNG(3840×2160 位图)并返回字节。 Future renderArchPng({ required ArchDoc doc, required Tokens baseTokens, required String projectName, }) async { final Tokens et = exportTokens(baseTokens); final ui.PictureRecorder recorder = ui.PictureRecorder(); final Canvas canvas = Canvas(recorder); const double w = 1920; const double h = 1080; canvas.scale(kExportPixelRatio); canvas.drawRect( const Rect.fromLTWH(0, 0, w, h), Paint()..color = Colors.white, ); // 标题与副标题(固定左上角)。 _text(canvas, '架构图设计', const Offset(48, 36), color: et.text, size: 34, weight: FontWeight.w700); _text(canvas, 'EDC|易得 · Easy Design Collection · 手绘识别架构图', const Offset(48, 88), color: et.sub, size: 16, weight: FontWeight.w400); // 内容适配(白底令牌 + 关闭网格点阵)。 final Rect b = doc.contentBounds().inflate(40); final ExportFit fit = _contentFit(b, kExportContentArea); canvas.save(); canvas.translate(fit.tx, fit.ty); ArchPainter( doc: doc.copyWith(zoom: fit.scale, panX: 0, panY: 0, gridSize: 0), t: et, ).paint(canvas, const Size(w, h)); canvas.restore(); _text( canvas, 'EDC|易得 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 ' '${doc.connectors.length} · 墨迹 ${doc.strokes.length}', Offset(48, h - 38), color: et.sub, size: 15, weight: FontWeight.w400, ); final ui.Image image = await recorder.endRecording().toImage( (w * kExportPixelRatio).toInt(), (h * kExportPixelRatio).toInt(), ); final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png); return data!.buffer.asUint8List(); } /// 内容适配:等比缩放并居中到 [area]。 ExportFit _contentFit(Rect bounds, Rect area) { if (bounds.width <= 1 || bounds.height <= 1) { return const ExportFit(1, 0, 0); } final double s = math .min(area.width / bounds.width, area.height / bounds.height) .clamp(0.1, 1.6) .toDouble(); final double tx = area.left + (area.width - bounds.width * s) / 2 - bounds.left * s; final double ty = area.top + (area.height - bounds.height * s) / 2 - bounds.top * s; return ExportFit(s, tx, ty); } /// 用统一字体绘制单行文本。 void _text( Canvas canvas, String s, Offset at, { required Color color, required double size, required FontWeight weight, }) { final TextPainter tp = TextPainter( text: TextSpan( text: s, style: TextStyle( color: color, fontSize: size, fontWeight: weight, fontFamily: 'Microsoft YaHei UI', fontFamilyFallback: const [ 'Microsoft YaHei', 'Noto Sans SC', 'sans-serif', ], ), ), textDirection: TextDirection.ltr, )..layout(); tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2)); } // ===================== SVG ===================== /// 构造架构图 SVG 文本(viewBox = 内容范围 + 留白;纯白背景)。 String buildArchSvg({required ArchDoc doc, required Tokens baseTokens}) { final Tokens t = exportTokens(baseTokens); final Rect b = doc.contentBounds().inflate(40); final double w = math.max(b.width, 200); final double h = math.max(b.height, 160); final StringBuffer sb = StringBuffer(); sb.writeln(''); sb.writeln( ''); sb.writeln(''); // 连线(底层)。 for (final ArchConnector c in doc.connectors) { if (!doc.isLayerVisible(c.layerId)) continue; _svgConnector(sb, doc, c); } // 图形。 for (final ArchShape s in doc.shapes) { if (!doc.isLayerVisible(s.layerId)) continue; _svgShape(sb, s, t); } // 手绘墨迹。 for (final ArchStroke s in doc.strokes) { if (!doc.isLayerVisible(s.layerId)) continue; sb.writeln( ''); } sb.writeln(''); return sb.toString(); } /// 连线(含正交折线、虚线、箭头与标签)。 void _svgConnector(StringBuffer sb, ArchDoc doc, ArchConnector c) { final ArchConnGeometry g = archConnectorGeometry(doc, c); final String d = _polyD(g.pts); final String color = _hex(c.color); final String dash = c.dash ? ' stroke-dasharray="8 6"' : ''; sb.writeln( ''); // 箭头(终点方向)。 if (g.pts.length >= 2) { final Offset a = g.pts[g.pts.length - 2]; final Offset b2 = g.end; final Offset dv = b2 - a; final double len = dv.distance; if (len > 1) { final Offset u = dv / len; final Offset n = Offset(-u.dy, u.dx); const double hl = 11; const double hw = 5.5; final Offset p1 = b2 - u * hl + n * hw; final Offset p2 = b2 - u * hl - n * hw; sb.writeln( ''); } } // 标签(白底片 + 文本)。 if (c.label.isNotEmpty) { final double lw = math.max(20, c.label.length * 10.5 + 10); final Rect bg = Rect.fromCenter(center: g.label, width: lw, height: 18); sb.writeln( ''); sb.writeln( '${_esc(c.label)}'); } } /// 单个标准图形。 void _svgShape(StringBuffer sb, ArchShape s, Tokens t) { final String fill = _hex(s.fill); final String fillOp = _op(s.fill); final String stroke = _hex(s.stroke); final String sw = _n(s.sw); final Rect r = s.rect; switch (s.type) { case ArchShapeType.rect: sb.writeln( ''); break; case ArchShapeType.roundRect: final double rad = math.min(s.radius, math.min(r.width, r.height) * 0.45); sb.writeln( ''); break; case ArchShapeType.ellipse: case ArchShapeType.circle: sb.writeln( ''); break; case ArchShapeType.triangle: sb.writeln( ''); break; case ArchShapeType.diamond: sb.writeln( ''); break; case ArchShapeType.hexagon: sb.writeln( ''); break; case ArchShapeType.cylinder: final double ry = math.min(r.height * 0.20, r.width * 0.32); final double l = r.left; final double rt = r.right; final double tp = r.top; final double bt = r.bottom; // 柱体(含底部弧)。 sb.writeln( ''); // 顶盖(稍亮)。 final double lidOp = math.min(1.0, (_opValue(s.fill) + 0.10)); sb.writeln( ''); break; case ArchShapeType.cloud: // 双层绘制:第一层带描边,第二层纯填充覆盖内部接缝 → 外轮廓保持描边。 final List circles = [ Offset(r.left + r.width * 0.24, r.top + r.height * 0.62), Offset(r.left + r.width * 0.42, r.top + r.height * 0.40), Offset(r.left + r.width * 0.64, r.top + r.height * 0.34), Offset(r.left + r.width * 0.82, r.top + r.height * 0.58), ]; final List radii = [ r.height * 0.26, r.height * 0.30, r.height * 0.28, r.height * 0.24, ]; final Rect base = Rect.fromLTRB( r.left + r.width * 0.06, r.top + r.height * 0.55, r.right - r.width * 0.06, r.top + r.height * 0.86, ); for (int pass = 0; pass < 2; pass++) { final bool strokePass = pass == 0; for (int i = 0; i < circles.length; i++) { sb.writeln( ''); } sb.writeln( ''); } break; case ArchShapeType.server: case ArchShapeType.client: case ArchShapeType.mobile: case ArchShapeType.firewall: case ArchShapeType.netSwitch: case ArchShapeType.queue: _svgItShape(sb, s, r, fill, fillOp, stroke, sw); break; case ArchShapeType.symbol: _svgSymbol(sb, s, r, fill, fillOp, stroke, sw); break; case ArchShapeType.text: break; case ArchShapeType.line: final Offset a = s.a ?? r.topLeft; final Offset b2 = s.b ?? r.bottomRight; sb.writeln( ''); if (s.arrow) { _svgArrow(sb, a, b2, stroke); } break; case ArchShapeType.polyline: if (s.pts.length >= 2) { sb.writeln( ''); } break; case ArchShapeType.curve: if (s.pts.length >= 2) { sb.writeln( ''); } break; } // 图内文字。 if (s.text.isNotEmpty) { final String tc = s.type == ArchShapeType.text ? _hex(s.stroke) : _hex(0xFF1B2740); double size = 12.5; if (s.type == ArchShapeType.text) { size = (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble(); } Offset center = s.rect.center; if (s.type == ArchShapeType.cloud) { center = center.translate(0, s.rect.height * 0.12); } else if (s.type == ArchShapeType.cylinder) { center = center.translate( 0, math.min(s.rect.height * 0.20, s.rect.width * 0.32) * 0.8); } else if (s.type == ArchShapeType.client) { center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.32); } else if (s.type == ArchShapeType.netSwitch) { center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.30); } _svgMultilineText(sb, s.text, center.dx, center.dy, tc, size); } } /// IT 图形(服务器 / PC / 移动端 / 防火墙 / 交换机 / 队列)的 SVG 绘制。 void _svgItShape(StringBuffer sb, ArchShape s, Rect r, String fill, String fillOp, String stroke, String sw) { final double rad = switch (s.type) { ArchShapeType.server => math.min(12.0, math.min(r.width, r.height) * 0.12), ArchShapeType.client => math.min(10.0, r.height * 0.08), ArchShapeType.mobile => math.min(16.0, r.width * 0.22), ArchShapeType.firewall => math.min(6.0, r.height * 0.10), ArchShapeType.netSwitch => math.min(10.0, r.height * 0.20), ArchShapeType.queue => r.height * 0.5, _ => 0.0, }; sb.writeln( ''); final String inner = 'stroke="$stroke" stroke-width="${_n(math.max(1, s.sw * 0.7))}" stroke-linecap="round"'; void hline(double y, double x0, double x1) { sb.writeln(''); } void dot(double x, double y, double radius) { sb.writeln( ''); } switch (s.type) { case ArchShapeType.server: for (int i = 1; i <= 3; i++) { final double y = r.top + r.height * i / 4; hline(y, r.left + r.width * 0.10, r.right - r.width * 0.10); } for (int i = 0; i < 4; i++) { dot(r.left + r.width * 0.16, r.top + r.height * (i + 0.5) / 4, math.min(2.4, r.width * 0.035)); } case ArchShapeType.client: final Rect screen = Rect.fromLTWH(r.left, r.top, r.width, r.height * 0.72); sb.writeln( ''); sb.writeln( ''); hline(r.bottom - r.height * 0.08, r.center.dx - r.width * 0.18, r.center.dx + r.width * 0.18); case ArchShapeType.mobile: hline(r.top + r.height * 0.055, r.center.dx - r.width * 0.14, r.center.dx + r.width * 0.14); hline(r.bottom - r.height * 0.05, r.center.dx - r.width * 0.12, r.center.dx + r.width * 0.12); case ArchShapeType.firewall: for (int i = 1; i < 3; i++) { hline(r.top + r.height * i / 3, r.left, r.right); } for (int i = 0; i < 3; i++) { final double y0 = r.top + r.height * i / 3; final double y1 = r.top + r.height * (i + 1) / 3; final double offset = i.isEven ? 0.5 : 0.25; for (double fx = offset; fx < 0.95; fx += 0.5) { final double x = r.left + r.width * fx; sb.writeln( ''); } } case ArchShapeType.netSwitch: final double size = math.min(r.height * 0.20, 8.0); for (int i = 0; i < 6; i++) { final double x = r.left + r.width * (0.10 + i * 0.135); sb.writeln( ''); } case ArchShapeType.queue: final double h = r.height * 0.30; for (int i = 0; i < 3; i++) { final double x = r.left + r.width * (0.30 + i * 0.18); sb.writeln( ''); } default: break; } } /// 图元库符号的 SVG 绘制(按 100×100 归一化基元映射到矩形)。 void _svgSymbol(StringBuffer sb, ArchShape s, Rect r, String fill, String fillOp, String stroke, String sw) { final LibSymbol? sym = SymbolCache.byId(s.symbolId); if (sym == null || s.symbolId.isEmpty) { sb.writeln( ''); return; } Offset p2(double x, double y) => symPt(x, y, r); final double rad = (r.width + r.height) / 2 / 100; for (final SymPrim p in sym.prims) { switch (p.kind) { case SymPrimKind.text: if (p.pts.length < 2 || p.label.isEmpty) break; final Offset tl = p2(p.pts[0], p.pts[1]); final double size = (r.height * 0.14).clamp(7.0, 18.0).toDouble(); sb.writeln( '${_esc(p.label)}'); case SymPrimKind.line: if (p.pts.length < 4) break; final Offset a = p2(p.pts[0], p.pts[1]); final Offset b = p2(p.pts[2], p.pts[3]); sb.writeln( ''); case SymPrimKind.polyline: if (p.pts.length < 4) break; final List pts = [ for (int i = 0; i + 1 < p.pts.length; i += 2) p2(p.pts[i], p.pts[i + 1]), ]; sb.writeln( ''); case SymPrimKind.circle: if (p.pts.length < 2) break; final Offset c = p2(p.pts[0], p.pts[1]); final double rr = p.r * rad; sb.writeln( ''); case SymPrimKind.rect: if (p.pts.length < 4) break; final Offset tl = p2(p.pts[0], p.pts[1]); sb.writeln( ''); case SymPrimKind.arc: if (p.pts.length < 2) break; final Offset c = p2(p.pts[0], p.pts[1]); final double rr = p.r * rad; final double a0 = p.startDeg * math.pi / 180; final double a1 = (p.startDeg + p.sweepDeg) * math.pi / 180; final Offset s0 = c + Offset(math.cos(a0) * rr, math.sin(a0) * rr); final Offset s1 = c + Offset(math.cos(a1) * rr, math.sin(a1) * rr); final int large = p.sweepDeg.abs() > 180 ? 1 : 0; final int sweep = p.sweepDeg >= 0 ? 1 : 0; sb.writeln( ''); } } } /// 箭头头部(line 图形用)。 void _svgArrow(StringBuffer sb, Offset a, Offset b, String color) { final Offset dv = b - a; final double len = dv.distance; if (len < 1) return; final Offset u = dv / len; final Offset n = Offset(-u.dy, u.dx); const double hl = 11; const double hw = 5.5; final Offset p1 = b - u * hl + n * hw; final Offset p2 = b - u * hl - n * hw; sb.writeln( ''); } /// 多行居中文本(每行一个 tspan)。 void _svgMultilineText( StringBuffer sb, String text, double cx, double cy, String color, double size) { final List lines = text.split('\n'); final double lineH = size * 1.25; final double startY = cy - (lines.length - 1) * lineH / 2; sb.writeln( ''); for (int i = 0; i < lines.length; i++) { sb.writeln( '${_esc(lines[i])}'); } sb.writeln(''); } // ===================== 工具 ===================== /// 数字格式化(最多 2 位小数、去掉多余 0)。 String _n(double v) { if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString(); return v.toStringAsFixed(2); } /// ARGB → `#rrggbb`。 String _hex(int argb) { final int rgb = argb & 0xFFFFFF; return '#${rgb.toRadixString(16).padLeft(6, '0')}'; } /// ARGB → 不透明度字符串。 String _op(int argb) => _opValue(argb).toStringAsFixed(3); /// ARGB → 不透明度值(0..1)。 double _opValue(int argb) => ((argb >> 24) & 0xFF) / 255; /// 点列表 → polygon points。 String _points(List pts) => pts.map((Offset p) => '${_n(p.dx)},${_n(p.dy)}').join(' '); /// 折线 d。 String _polyD(List pts) { if (pts.isEmpty) return ''; final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); for (int i = 1; i < pts.length; i++) { sb.write(' L ${_n(pts[i].dx)} ${_n(pts[i].dy)}'); } return sb.toString(); } /// 样条 d(Catmull-Rom → 三次贝塞尔,与画布绘制一致)。 String _splineD(List pts) { if (pts.isEmpty) return ''; final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); if (pts.length == 2) { sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}'); return sb.toString(); } for (int i = 0; i < pts.length - 1; i++) { final Offset p0 = i == 0 ? pts[i] : pts[i - 1]; final Offset p1 = pts[i]; final Offset p2 = pts[i + 1]; final Offset p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1]; final Offset c1 = p1 + (p2 - p0) / 6; final Offset c2 = p2 - (p3 - p1) / 6; sb.write( ' C ${_n(c1.dx)} ${_n(c1.dy)} ${_n(c2.dx)} ${_n(c2.dy)} ${_n(p2.dx)} ${_n(p2.dy)}'); } return sb.toString(); } /// 平滑墨迹 d(与画布 `archSmoothPath` 一致的二次贝塞尔)。 String _smoothD(List pts) { if (pts.isEmpty) return ''; final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}'); if (pts.length == 2) { sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}'); return sb.toString(); } for (int i = 1; i < pts.length - 1; i++) { final Offset mid = (pts[i] + pts[i + 1]) / 2; sb.write(' Q ${_n(pts[i].dx)} ${_n(pts[i].dy)} ${_n(mid.dx)} ${_n(mid.dy)}'); } sb.write(' L ${_n(pts.last.dx)} ${_n(pts.last.dy)}'); return sb.toString(); } /// XML 文本转义。 String _esc(String s) => s .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"');