90 lines
2.3 KiB
Dart
90 lines
2.3 KiB
Dart
import 'dart:ui' as ui;
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/rendering.dart';
|
|
import 'dart:typed_data';
|
|
import 'dart:io';
|
|
import 'dart:ui' as ui;
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/rendering.dart';
|
|
import 'dart:typed_data';
|
|
import 'dart:io';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
class DrawScreen extends StatefulWidget {
|
|
@override
|
|
_DrawScreenState createState() => _DrawScreenState();
|
|
}
|
|
|
|
class _DrawScreenState extends State<DrawScreen> {
|
|
GlobalKey _globalKey = GlobalKey();
|
|
bool _imageSaved = false;
|
|
|
|
Future<Uint8List?> _capturePng() async {
|
|
try {
|
|
RenderRepaintBoundary? boundary =
|
|
_globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary?;
|
|
ui.Image image = await boundary!.toImage();
|
|
ByteData? byteData =
|
|
await image.toByteData(format: ui.ImageByteFormat.png);
|
|
Uint8List pngBytes = byteData!.buffer.asUint8List();
|
|
return pngBytes;
|
|
} catch (e) {
|
|
print(e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Text('Draw and Save'),
|
|
),
|
|
body: Column(
|
|
children: [
|
|
Expanded(
|
|
child: RepaintBoundary(
|
|
key: _globalKey,
|
|
child: CustomPaint(
|
|
painter: MyPainter(),
|
|
),
|
|
),
|
|
),
|
|
FilledButton(
|
|
child: Text('Save'),
|
|
onPressed: () async {
|
|
Uint8List? pngBytes = await _capturePng();
|
|
if (pngBytes != null) {
|
|
String path =
|
|
'${(await getApplicationDocumentsDirectory()).path}/example.png';
|
|
await File(path).writeAsBytes(pngBytes);
|
|
setState(() {
|
|
_imageSaved = true;
|
|
});
|
|
}
|
|
},
|
|
),
|
|
if (_imageSaved) Text('Image saved successfully!'),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class MyPainter extends CustomPainter {
|
|
@override
|
|
void paint(Canvas canvas, Size size) {
|
|
Paint paint = Paint()
|
|
..color = Colors.red
|
|
..strokeWidth = 2
|
|
..style = PaintingStyle.stroke;
|
|
|
|
canvas.drawCircle(Offset(size.width / 2, size.height / 2), 50, paint);
|
|
}
|
|
|
|
@override
|
|
bool shouldRepaint(CustomPainter oldDelegate) {
|
|
return false;
|
|
}
|
|
}
|