Files
kanimaji-dart/lib/widget.dart
T
2026-02-22 16:12:31 +09:00

352 lines
10 KiB
Dart

import 'dart:async';
import 'dart:ui' as ui;
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kanimaji/animator.dart';
import 'package:kanimaji/kanjivg_parser.dart';
Future<KanjiVGItem> _defaultKanjiDataProvider(String kanji) async {
final hex = kanji.runes.isEmpty
? '00000'
: kanji.runes.first.toRadixString(16).padLeft(5, '0');
final assetPath = 'assets/kanjivg/kanji/$hex.svg';
final svgString = await rootBundle.loadString(assetPath);
return KanjiVGItem.parseFromXml(svgString);
}
class Kanimaji extends StatefulWidget {
final String kanji;
final FutureOr<KanjiVGItem> Function(String kanji) kanjiDataProvider;
// Animation parameters
final bool loop;
// final Duration delayBetweenStrokes;
// final Duration delayBetweenLoops;
// TODO: add support for specifying animation bezier curve
// final Cubic animationCurve;
// final double speed;
// Brush parameters
final bool showBrush;
final Color brushColor;
final double brushRadius;
// Stroke parameters
final Color strokeColor;
final Color strokeUnfilledColor;
final double strokeWidth;
final Color backgroundColor;
// TODO: add support for drawing stroke numbers
// final bool showStrokeNumbers;
// final Color strokeNumberColor;
// final double strokeNumberFontSize;
// final String strokeNumberFontFamily;
// TODO: add support for drawing stipled cross
// final bool showCross;
// final Color crossColor;
// final double crossStrokeWidth;
// final double crossStipleLength;
// final double crossStipleGap;
const Kanimaji({
super.key,
required this.kanji,
this.kanjiDataProvider = _defaultKanjiDataProvider,
this.loop = true,
this.strokeColor = Colors.black,
this.strokeUnfilledColor = const Color(0xFFEEEEEE),
this.strokeWidth = 3.0,
this.backgroundColor = Colors.transparent,
this.showBrush = true,
this.brushColor = Colors.red,
this.brushRadius = 4.0,
});
@override
State<Kanimaji> createState() => _KanimajiState();
}
class _KanimajiState extends State<Kanimaji>
with SingleTickerProviderStateMixin {
KanjiVGItem? _kanjiData;
String? _error;
late AnimationController _controller;
List<double> get _pathLengths =>
_kanjiData?.paths
.map((p) => p.svgPath.size(error: 1e-8).toDouble())
.toList() ??
[];
List<double> get _pathDurations =>
_pathLengths.map((len) => strokeLengthToDuration(len)).toList();
static const double _viewBoxWidth = 109.0;
static const double _viewBoxHeight = 109.0;
// // total length summation (for drawing metrics)
// double _totalLength = 0.0;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this);
_controller.addListener(_onTick);
_loadAndParseSvg().then((_) => _configureController());
}
// @override
// void didUpdateWidget(covariant Kanimaji oldWidget) {
// super.didUpdateWidget(oldWidget);
// // If kanji changed, re-load
// if (oldWidget.kanji != widget.kanji) {
// _loadAndParseSvg();
// } else if (oldWidget.speed != widget.speed ||
// oldWidget.durationOverride != widget.durationOverride ||
// oldWidget.loop != widget.loop) {
// // Update controller if animation parameters changed
// _configureController();
// }
// }
void _onTick() {
if (mounted) setState(() {});
}
@override
void dispose() {
_controller.removeListener(_onTick);
_controller.dispose();
super.dispose();
}
Future<void> _loadAndParseSvg() async {
try {
final data = await widget.kanjiDataProvider(widget.kanji);
setState(() {
_kanjiData = data;
_error = null;
});
} catch (e) {
setState(() {
_kanjiData = null;
_error = 'Error loading/parsing kanji data: $e';
});
}
}
void _configureController() {
if (_kanjiData == null) return;
final double totalSec = _pathDurations.fold(0.0, (a, b) => a + b);
// final double scaledTotalSec = (widget.speed <= 0) ? totalSec : (totalSec / widget.speed);
// final Duration duration = widget.durationOverride ??
// Duration(milliseconds: (math.max(0.001, scaledTotalSec) * 1000.0).round());
_controller.stop();
_controller.duration = Duration(milliseconds: (totalSec * 1000.0).round());
if (widget.loop) {
_controller.repeat();
} else {
_controller.forward(from: 0);
}
}
@override
Widget build(BuildContext context) {
if (_kanjiData == null && _error == null) {
return SizedBox.expand(child: Center(child: CircularProgressIndicator()));
}
if (_error != null) {
return SizedBox.expand(child: ErrorWidget(_error!));
}
return FittedBox(
child: SizedBox(
width: _viewBoxWidth,
height: _viewBoxHeight,
child: CustomPaint(
painter: _KanimajiPainter(
paths: _kanjiData!.paths.map((p) => p.svgPath.toUiPath()).toList(),
pathLengths: _pathLengths,
pathDurations: _pathDurations,
progress: _controller.value,
strokeColor: widget.strokeColor,
strokeUnfilledColor: widget.strokeUnfilledColor,
strokeWidth: widget.strokeWidth,
backgroundColor: widget.backgroundColor,
viewBoxWidth: _viewBoxWidth,
viewBoxHeight: _viewBoxHeight,
showBrush: widget.showBrush,
brushColor: widget.brushColor,
brushRadius: widget.brushRadius,
),
),
),
);
}
}
class _KanimajiPainter extends CustomPainter {
final double progress; // 0..1
final List<ui.Path> paths;
final List<double> pathLengths;
final List<double> pathDurations;
// TODO: don't recalculate these all the time, compute once and cache
List<double> get absolutePathDurations {
final List<double> absolute = [];
double sum = 0.0;
for (final dur in pathDurations) {
absolute.add(sum);
sum += dur;
}
return absolute;
}
final double viewBoxWidth;
final double viewBoxHeight;
final Color strokeColor;
final Color strokeUnfilledColor;
final double strokeWidth;
final Color backgroundColor;
final bool showBrush;
final Color brushColor;
final double brushRadius;
_KanimajiPainter({
required this.progress,
required this.paths,
required this.pathLengths,
required this.pathDurations,
required this.viewBoxWidth,
required this.viewBoxHeight,
required this.strokeColor,
required this.strokeUnfilledColor,
required this.strokeWidth,
required this.backgroundColor,
required this.showBrush,
required this.brushColor,
required this.brushRadius,
});
@override
void paint(Canvas canvas, Size size) {
final bgPaint = Paint()..color = backgroundColor;
canvas.drawRect(Offset.zero & size, bgPaint);
if (paths.isEmpty) return;
final double sx = size.width / viewBoxWidth;
final double sy = size.height / viewBoxHeight;
final double scale = math.min(sx, sy);
final double dx = (size.width - viewBoxWidth * scale) / 2.0;
final double dy = (size.height - viewBoxHeight * scale) / 2.0;
final Paint unfilledPaint = Paint()
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = strokeWidth / scale
..color = strokeUnfilledColor;
final Paint filledPaint = Paint()
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = strokeWidth / scale
..color = strokeColor;
final Paint brushPaint = Paint()
..style = PaintingStyle.fill
..color = brushColor;
for (final path in paths) {
canvas.drawPath(path, unfilledPaint);
}
canvas.save();
canvas.translate(dx, dy);
canvas.scale(scale, scale);
// total animation time in seconds computed from durations
final double totalTime = pathDurations.isEmpty
? 1.0
: pathDurations.fold(0.0, (a, b) => a + b);
final double p = progress.clamp(0.0, 1.0);
final int currentlyDrawingIndex = absolutePathDurations.lastIndexWhere(
(t) => t <= p * totalTime,
);
if (currentlyDrawingIndex == -1) {
for (final path in paths) {
canvas.drawPath(path, filledPaint);
}
canvas.restore();
return;
}
// Draw all completed strokes fully filled
for (int i = 0; i < currentlyDrawingIndex; i++) {
canvas.drawPath(paths[i], filledPaint);
}
// Draw the currently drawing stroke with partial coverage
if (currentlyDrawingIndex >= 0 && currentlyDrawingIndex < paths.length) {
final ui.Path path = paths[currentlyDrawingIndex];
final double len = pathLengths[currentlyDrawingIndex];
final double dur = pathDurations[currentlyDrawingIndex];
final relativeElapsedTime =
p * totalTime -
(currentlyDrawingIndex > 0
? absolutePathDurations[currentlyDrawingIndex]
: 0.0);
final double strokeProgress = (relativeElapsedTime / dur).clamp(0.0, 1.0);
final ui.PathMetrics metrics = path.computeMetrics();
final ui.PathMetric metric = metrics.first;
final double drawLength = len * strokeProgress;
final ui.Path partialPath = metric.extractPath(0, drawLength);
canvas.drawPath(partialPath, filledPaint);
if (showBrush) {
final ui.Tangent? tangent = metric.getTangentForOffset(drawLength);
if (tangent != null) {
canvas.drawCircle(tangent.position, brushRadius / scale, brushPaint);
}
}
}
canvas.restore();
}
@override
bool shouldRepaint(covariant _KanimajiPainter oldDelegate) {
return oldDelegate.progress != progress ||
oldDelegate.paths != paths ||
oldDelegate.strokeColor != strokeColor ||
oldDelegate.strokeUnfilledColor != strokeUnfilledColor ||
oldDelegate.strokeWidth != strokeWidth ||
oldDelegate.backgroundColor != backgroundColor ||
oldDelegate.showBrush != showBrush ||
oldDelegate.brushColor != brushColor ||
oldDelegate.brushRadius != brushRadius;
}
}