aded preview for sharing targets.

This commit is contained in:
Jan Pleterski
2026-11-13 11:15:01 +01:00
parent 30708c73b1
commit f6974e3e26
5 changed files with 472 additions and 0 deletions
+361
View File
@@ -0,0 +1,361 @@
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import '../screens/target_view.dart' show BarChartPainter;
/// Everything the share image shows, taken from the target view as it is.
class ResultShareData {
final String title; // session (folder) name
final String date; // already formatted, e.g. 12.11.2026
final String countsLine; // e.g. "7 tarč · 35 strelov"
final int total;
final double? averagePerShot;
final Uint8List targetImage; // the selected target design
final Size targetImageSize;
final List<Offset> bullets; // in targetImage pixels
final double bulletDiameter; // in targetImage pixels
final Color bulletColor;
final Color targetBackground; // matches the target design
final List<(String top, String bottom)> tiles; // e.g. ("6x", "10")
final List<MapEntry<int, int>> chart; // bar label number -> points
final bool chartPerShot; // bars are shots of one target, not targets of a session
final String Function(String) t;
const ResultShareData({
required this.title,
required this.date,
required this.countsLine,
required this.total,
required this.averagePerShot,
required this.targetImage,
required this.targetImageSize,
required this.bullets,
required this.bulletDiameter,
required this.bulletColor,
required this.targetBackground,
required this.tiles,
required this.chart,
required this.chartPerShot,
required this.t,
});
}
bool _sharing = false;
/// Builds the result image off screen and opens the phone's share menu with it.
Future<void> shareResult(BuildContext context, ResultShareData data) async {
if (_sharing) return; // double tap
_sharing = true;
final overlay = Overlay.of(context);
final messenger = ScaffoldMessenger.maybeOf(context);
final key = GlobalKey();
OverlayEntry? entry;
try {
// Decode the target first so it is in the very first frame
await precacheImage(MemoryImage(data.targetImage), context);
// Laid out and painted, but outside the screen
entry = OverlayEntry(
builder: (_) => Positioned(
left: -ResultShareCard.size.width - 100,
top: 0,
child: IgnorePointer(
child: RepaintBoundary(key: key, child: ResultShareCard(data: data)),
),
),
);
overlay.insert(entry);
await WidgetsBinding.instance.endOfFrame;
final render = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
if (render.debugNeedsPaint) await WidgetsBinding.instance.endOfFrame;
// Card is 960x540 logical: pixel ratio 2 gives a 1920x1080 image
final image = await render.toImage(pixelRatio: 2);
final png = await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
entry.remove();
entry = null;
final dir = await getTemporaryDirectory();
final file = File(
'${dir.path}/sdk_kovinar_${DateTime.now().millisecondsSinceEpoch}.png');
await file.writeAsBytes(png!.buffer.asUint8List());
await SharePlus.instance.share(ShareParams(
files: [XFile(file.path, mimeType: 'image/png')],
text: '${data.title} · ${data.total}',
));
} catch (e) {
debugPrint('Share failed: $e');
messenger?.showSnackBar(SnackBar(content: Text(data.t('Sharing failed'))));
} finally {
entry?.remove();
_sharing = false;
}
}
/// The 960x540 image: header with the result, target with score tiles on the
/// left, the bar chart with every value on the right.
class ResultShareCard extends StatelessWidget {
static const Size size = Size(960, 540);
final ResultShareData data;
const ResultShareCard({super.key, required this.data});
@override
Widget build(BuildContext context) {
final t = data.t;
final accent = data.bulletColor;
return SizedBox.fromSize(
size: size,
child: Material(
color: const Color(0xFF1B1E21),
child: Padding(
padding: const EdgeInsets.fromLTRB(28, 22, 28, 22),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('SDK KOVINAR',
style: TextStyle(
color: accent,
fontSize: 12,
fontWeight: FontWeight.w800,
letterSpacing: 2.5)),
const SizedBox(height: 2),
Text(data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.w800)),
const SizedBox(height: 2),
Text('${data.date} · ${data.countsLine}',
style: const TextStyle(
color: Colors.white60, fontSize: 14)),
],
),
),
if (data.averagePerShot != null)
_HeaderFigure(
label: t('Average per shot'),
value: data.averagePerShot!.toStringAsFixed(2),
size: 40),
const SizedBox(width: 28),
_HeaderFigure(
label: t('Total score').replaceAll(':', ''),
value: '${data.total}',
size: 40,
color: accent),
],
),
const SizedBox(height: 16),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Target and score tiles
Container(
width: 380,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: data.targetBackground,
borderRadius: BorderRadius.circular(18),
),
child: Column(
children: [
Expanded(
child: Center(
child: AspectRatio(
aspectRatio: data.targetImageSize.width /
data.targetImageSize.height,
child: _TargetWithHits(data: data),
),
),
),
const SizedBox(height: 10),
SizedBox(
height: 58,
child: Row(
children: [
for (final (top, bottom) in data.tiles)
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 3),
child: _Tile(
top: top,
bottom: bottom,
color: accent),
),
),
],
),
),
],
),
),
const SizedBox(width: 16),
// Chart with every value
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 4),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(18),
),
child: CustomPaint(
size: Size.infinite,
painter: BarChartPainter(
data: data.chart,
maxScore: _chartMax(data),
bulletColor: accent,
isShotView: data.chartPerShot,
backgroundColor: Colors.white,
translateFunc: t,
xAxisLabelKey: data.chartPerShot ? 'Points' : null,
),
),
),
),
],
),
),
],
),
),
),
);
}
static double _chartMax(ResultShareData d) {
final max = d.chart.isEmpty
? 0
: d.chart.map((e) => e.value).reduce((a, b) => a > b ? a : b);
return max <= 0 ? 1 : max.toDouble();
}
}
class _HeaderFigure extends StatelessWidget {
final String label;
final String value;
final double size;
final Color color;
const _HeaderFigure(
{required this.label,
required this.value,
required this.size,
this.color = Colors.white});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Text(label.toUpperCase(),
style: const TextStyle(
color: Colors.white54,
fontSize: 11,
fontWeight: FontWeight.w700,
letterSpacing: 1.5)),
Text(value,
style: TextStyle(
color: color,
fontSize: size,
height: 1.05,
fontWeight: FontWeight.w800,
fontFeatures: const [FontFeature.tabularFigures()])),
],
);
}
}
class _TargetWithHits extends StatelessWidget {
final ResultShareData data;
const _TargetWithHits({required this.data});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, c) {
final scale = c.maxWidth / data.targetImageSize.width;
final d = data.bulletDiameter * scale;
return Stack(
children: [
Positioned.fill(
child: Image.memory(data.targetImage,
fit: BoxFit.fill, gaplessPlayback: true)),
for (final b in data.bullets)
Positioned(
left: b.dx * scale - d / 2,
top: b.dy * scale - d / 2,
width: d,
height: d,
child: DecoratedBox(
decoration: BoxDecoration(
color: data.bulletColor.withValues(alpha: 0.85),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 1),
),
),
),
],
);
});
}
}
class _Tile extends StatelessWidget {
final String top;
final String bottom;
final Color color;
const _Tile({required this.top, required this.bottom, required this.color});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
children: [
Container(
height: 20,
width: double.infinity,
color: const Color(0xFF2C2F33),
alignment: Alignment.center,
child: FittedBox(
child: Text(top,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w700)),
),
),
Expanded(
child: Container(
width: double.infinity,
color: color.withValues(alpha: 0.9),
alignment: Alignment.center,
child: FittedBox(
child: Text(bottom,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w800)),
),
),
),
],
),
);
}
}