gen_golden.dart 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // There's probably some better way to do this, but for now run `flutter test tool/gen_golden.dart
  2. // should exclude files that
  3. // - aren't rendering properly
  4. // - have text (this doesn't render properly in the host setup?)
  5. // The golden files should then be visually compared against Chrome's rendering output for correctness.
  6. // The comparison may have to be made more tolerant if we want to use other sources of rendering for comparison...
  7. import 'dart:async';
  8. import 'dart:io';
  9. import 'dart:typed_data';
  10. import 'dart:ui';
  11. import 'package:path/path.dart' as path;
  12. import 'package:flutter_svg/svg.dart';
  13. import 'package:flutter_svg/src/vector_drawable.dart';
  14. Future<Uint8List> getSvgPngBytes(String svgData) async {
  15. final PictureRecorder rec = PictureRecorder();
  16. final Canvas canvas = Canvas(rec);
  17. const Size size = Size(200.0, 200.0);
  18. final DrawableRoot svgRoot =
  19. await svg.fromSvgString(svgData, 'GenGoldenTest');
  20. svgRoot.scaleCanvasToViewBox(canvas, size);
  21. svgRoot.clipCanvasToViewBox(canvas);
  22. canvas.drawPaint(Paint()..color = const Color(0xFFFFFFFF));
  23. svgRoot.draw(canvas, svgRoot.viewport.viewBoxRect);
  24. final Picture pict = rec.endRecording();
  25. final Image image =
  26. await pict.toImage(size.width.toInt(), size.height.toInt());
  27. final ByteData bytes = await image.toByteData(format: ImageByteFormat.png);
  28. return bytes.buffer.asUint8List();
  29. }
  30. Iterable<File> getSvgFileNames() sync* {
  31. final Directory dir = Directory('./example/assets');
  32. for (FileSystemEntity fe in dir.listSync(recursive: true)) {
  33. if (fe is File && fe.path.toLowerCase().endsWith('.svg')) {
  34. // Skip text based tests unless we're on Linux - these have
  35. // subtle platform specific differences.
  36. if (fe.path.toLowerCase().contains('text') && !Platform.isLinux) {
  37. continue;
  38. }
  39. yield fe;
  40. }
  41. }
  42. }
  43. String getGoldenFileName(String svgAssetPath) {
  44. return svgAssetPath
  45. .replaceAll('/example\/assets/', '/golden/')
  46. .replaceAll('\\example\\assets\\', '\\golden\\')
  47. .replaceAll('.svg', '.png');
  48. }
  49. Future<void> main() async {
  50. for (File fe in getSvgFileNames()) {
  51. final String pathName = getGoldenFileName(fe.path);
  52. final Directory goldenDir = Directory(path.dirname(pathName));
  53. if (!goldenDir.existsSync()) {
  54. goldenDir.createSync(recursive: true);
  55. }
  56. final File output = File(pathName);
  57. print(pathName);
  58. await output.writeAsBytes(await getSvgPngBytes(await fe.readAsString()));
  59. }
  60. }